1 /* Copyright (c) 2009, 2021, Oracle and/or its affiliates.
2 
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License, version 2.0,
5    as published by the Free Software Foundation.
6 
7    This program is also distributed with certain software (including
8    but not limited to OpenSSL) that is licensed under separate terms,
9    as designated in a particular file or component or in included license
10    documentation.  The authors of MySQL hereby grant you an additional
11    permission to link the program and your derivative works with the
12    separately licensed software that they have included with MySQL.
13 
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License, version 2.0, for more details.
18 
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software Foundation,
21    51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */
22 
23 /**
24   == Debug Sync Facility ==
25 
26   The Debug Sync Facility allows placement of synchronization points in
27   the server code by using the DEBUG_SYNC macro:
28 
29       open_tables(...)
30 
31       DEBUG_SYNC(thd, "after_open_tables");
32 
33       lock_tables(...)
34 
35   When activated, a sync point can
36 
37     - Emit a signal(s) and/or
38     - Wait for a signal
39 
40   Nomenclature:
41 
42     - signal:             An event identified by a name that a signal
43                           thread uses to notify the wait thread that
44                           waits on this event. When the signal  thread
45                           notifies the wait thread, the signal name
46                           is copied into global list and the wait thread
47                           is signalled to wake up and proceed with further
48                           processing.
49 
50     - emit a signal:      Signal thread wakes up wait thread or multiple
51                           wait threads that shall wait for the signal identified
52                           by a signal name. This signal thread copies the signal
53                           name into a global list and broadcasts the event which
54                           wakes the threads that wait for this event.
55 
56     - wait for a signal:  Wait on a event indentified by the signal name until
57                           the signal thread signals the event.
58 
59   By default, all sync points are inactive. They do nothing (except to
60   burn a couple of CPU cycles for checking if they are active).
61 
62   A sync point becomes active when an action is requested for it.
63   To do so, put a line like this in the test case file:
64 
65       SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed';
66 
67   This activates the sync point 'after_open_tables'. It requests it to
68   emit the signal 'opened' and wait for another thread to emit the signal
69   'flushed' when the thread's execution runs through the sync point.
70 
71   For every sync point there can be one action per thread only. Every
72   thread can request multiple actions, but only one per sync point. In
73   other words, a thread can activate multiple sync points.
74 
75   However a single action can emit several signals, example given:
76 
77       SET DEBUG_SYNC= 'after_open_tables SIGNAL a,b,c WAIT_FOR flushed';
78 
79   Suppose we had several connections, and each one could possibly emit
80   signal 'after_latch'. Let assume there is another connection, which
81   waits for the signal being emitted. If the waiting connection wanted
82   to recognize, which connection emitted 'after_latch', then we could
83   decide to always emit two signals: 'after_latch' and 'con$id', where
84   con$id would describe uniquely each connection (con1, con2, ...).
85   Then the waiting connection could simply perform SELECT @@DEBUG_SYNC,
86   and search for con* there. To remove such con$id from @@DEBUG_SYNC,
87   one could then simply perform SET DEBUG_SYNC= 'now WAIT_FOR con$id'.
88 
89   Here is an example how to activate and use the sync points:
90 
91       --connection conn1
92       SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed';
93       send INSERT INTO t1 VALUES(1);
94           --connection conn2
95           SET DEBUG_SYNC= 'now WAIT_FOR opened';
96           SET DEBUG_SYNC= 'after_abort_locks SIGNAL flushed';
97           FLUSH TABLE t1;
98 
99   When conn1 runs through the INSERT statement, it hits the sync point
100   'after_open_tables'. It notices that it is active and executes its
101   action. It emits the signal 'opened' and waits for another thread to
102   emit the signal 'flushed'.
103 
104   conn2 waits immediately at the special sync point 'now' for another
105   thread to emit the 'opened' signal.
106 
107   If conn1 signals 'opened' before conn2 reaches 'now', conn2 will find
108   the 'opened' signal. The wait thread shall not wait in this case.
109 
110   When conn2 reaches 'after_abort_locks', it signals 'flushed', which lets
111   conn1 awake and clears the 'flushed' signal from the global list. In case
112   the 'flushed' signal is to be notified to multiple wait threads, an attribute
113   NO_CLEAR_EVENT need to be specified with the WAIT_FOR in addition to signal
114   the name as:
115       SET DEBUG_SYNC= 'WAIT_FOR flushed NO_CLEAR_EVENT';
116   It is up to the user to ensure once when all the wait threads have processed
117   the 'flushed' signal to clear/deactivate the signal using the RESET action
118   of DEBUG_SYNC accordingly.
119 
120 
121   Normally the activation of a sync point is cleared when it has been
122   executed. Sometimes it is necessary to keep the sync point active for
123   another execution. You can add an execute count to the action:
124 
125       SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 3';
126 
127   This sets the signal point's activation counter to 3. Each execution
128   decrements the counter. After the third execution the sync point
129   becomes inactive.
130 
131   One of the primary goals of this facility is to eliminate sleeps from
132   the test suite. In most cases it should be possible to rewrite test
133   cases so that they do not need to sleep. (But this facility cannot
134   synchronize multiple processes.) However, to support test development,
135   and as a last resort, sync point waiting times out. There is a default
136   timeout, but it can be overridden:
137 
138       SET DEBUG_SYNC= 'name WAIT_FOR sig TIMEOUT 10 EXECUTE 2';
139 
140   TIMEOUT 0 is special: If the signal is not present, the wait times out
141   immediately.
142 
143   When a wait timed out (even on TIMEOUT 0), a warning is generated so
144   that it shows up in the test result.
145 
146   You can throw an error message and kill the query when a synchronization
147   point is hit a certain number of times:
148 
149       SET DEBUG_SYNC= 'name HIT_LIMIT 3';
150 
151   Or combine it with signal and/or wait:
152 
153       SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 2 HIT_LIMIT 3';
154 
155   Here the first two hits emit the signal, the third hit returns the error
156   message and kills the query.
157 
158   For cases where you are not sure that an action is taken and thus
159   cleared in any case, you can force to clear (deactivate) a sync point:
160 
161       SET DEBUG_SYNC= 'name CLEAR';
162 
163   If you want to clear all actions and clear the global signal, use:
164 
165       SET DEBUG_SYNC= 'RESET';
166 
167   This is the only way to reset the global signal to an empty string.
168 
169   For testing of the facility itself you can execute a sync point just
170   as if it had been hit:
171 
172       SET DEBUG_SYNC= 'name TEST';
173 
174 
175   === Formal Syntax ===
176 
177   The string to "assign" to the DEBUG_SYNC variable can contain:
178 
179       {RESET |
180        <sync point name> TEST |
181        <sync point name> CLEAR |
182        <sync point name> {{SIGNAL <signal name>[, <signal name>]* |
183                            WAIT_FOR <signal name> [TIMEOUT <seconds>]
184                            [NO_CLEAR_EVENT]}
185                           [EXECUTE <count>] &| HIT_LIMIT <count>}}
186 
187   Here '&|' means 'and/or'. This means that one of the sections
188   separated by '&|' must be present or both of them.
189 
190 
191   === Activation/Deactivation ===
192 
193   The facility is an optional part of the MySQL server.
194   It is enabled in a debug server by default.
195 
196   The Debug Sync Facility, when compiled in, is disabled by default. It
197   can be enabled by a mysqld command line option:
198 
199       --debug-sync-timeout[=default_wait_timeout_value_in_seconds]
200 
201   'default_wait_timeout_value_in_seconds' is the default timeout for the
202   WAIT_FOR action. If set to zero, the facility stays disabled.
203 
204   The facility is enabled by default in the test suite, but can be
205   disabled with:
206 
207       mysql-test-run.pl ... --debug-sync-timeout=0 ...
208 
209   Likewise the default wait timeout can be set:
210 
211       mysql-test-run.pl ... --debug-sync-timeout=10 ...
212 
213   The command line option influences the readable value of the system
214   variable 'debug_sync'.
215 
216   * If the facility is not compiled in, the system variable does not exist.
217 
218   * If --debug-sync-timeout=0 the value of the variable reads as "OFF".
219 
220   * Otherwise the value reads as "ON - current signal: " followed by the
221     current signal string, which can be empty.
222 
223   The readable variable value is the same, regardless if read as global
224   or session value.
225 
226   Setting the 'debug-sync' system variable requires 'SUPER' privilege.
227   You can never read back the string that you assigned to the variable,
228   unless you assign the value that the variable does already have. But
229   that would give a parse error. A syntactically correct string is
230   parsed into a debug sync action and stored apart from the variable value.
231 
232 
233   === Implementation ===
234 
235   Pseudo code for a sync point:
236 
237       #define DEBUG_SYNC(thd, sync_point_name)
238                 if (unlikely(opt_debug_sync_timeout))
239                   debug_sync(thd, STRING_WITH_LEN(sync_point_name))
240 
241   The sync point performs a binary search in a sorted array of actions
242   for this thread.
243 
244   The SET DEBUG_SYNC statement adds a requested action to the array or
245   overwrites an existing action for the same sync point. When it adds a
246   new action, the array is sorted again.
247 
248 
249   === A typical synchronization pattern ===
250 
251   There are quite a few places in MySQL, where we use a synchronization
252   pattern like this:
253 
254   mysql_mutex_lock(&mutex);
255   thd->enter_cond(&condition_variable, &mutex, new_message);
256   #if defined(ENABLE_DEBUG_SYNC)
257   if (!thd->killed && !end_of_wait_condition)
258      DEBUG_SYNC(thd, "sync_point_name");
259   #endif
260   while (!thd->killed && !end_of_wait_condition)
261     mysql_cond_wait(&condition_variable, &mutex);
262   mysql_mutex_unlock(&mutex);
263   thd->exit_cond(old_message);
264 
265   Here some explanations:
266 
267   thd->enter_cond() is used to register the condition variable and the
268   mutex in THD::current_cond/current_mutex. This is done to allow the
269   thread to be interrupted (killed) from its sleep. Another thread can
270   find the condition variable to signal and mutex to use for synchronization
271   in this thread's THD.
272 
273   thd->enter_cond() requires the mutex to be acquired in advance.
274 
275   thd->exit_cond() unregisters the condition variable and mutex. Requires
276   the mutex to be released in advance.
277 
278   If you want to have a Debug Sync point with the wait, please place it
279   behind enter_cond(). Only then you can safely decide, if the wait will
280   be taken. Also you will have THD::proc_info correct when the sync
281   point emits a signal. DEBUG_SYNC sets its own proc_info, but restores
282   the previous one before releasing its internal mutex. As soon as
283   another thread sees the signal, it does also see the proc_info from
284   before entering the sync point. In this case it will be "new_message",
285   which is associated with the wait that is to be synchronized.
286 
287   In the example above, the wait condition is repeated before the sync
288   point. This is done to skip the sync point, if no wait takes place.
289   The sync point is before the loop (not inside the loop) to have it hit
290   once only. It is possible that the condition variable is signaled
291   multiple times without the wait condition to be true.
292 
293   A bit off-topic: At some places, the loop is taken around the whole
294   synchronization pattern:
295 
296   while (!thd->killed && !end_of_wait_condition)
297   {
298     mysql_mutex_lock(&mutex);
299     thd->enter_cond(&condition_variable, &mutex, new_message);
300     if (!thd->killed [&& !end_of_wait_condition])
301     {
302       [DEBUG_SYNC(thd, "sync_point_name");]
303       mysql_cond_wait(&condition_variable, &mutex);
304     }
305     mysql_mutex_unlock(&mutex);
306     thd->exit_cond(old_message);
307   }
308 
309   Note that it is important to repeat the test for thd->killed after
310   enter_cond(). Otherwise the killing thread may kill this thread after
311   it tested thd->killed in the loop condition and before it registered
312   the condition variable and mutex in enter_cond(). In this case, the
313   killing thread does not know that this thread is going to wait on a
314   condition variable. It would just set THD::killed. But if we would not
315   test it again, we would go asleep though we are killed. If the killing
316   thread would kill us when we are after the second test, but still
317   before sleeping, we hold the mutex, which is registered in THD.
318   The killing thread would try to acquire the mutex before signaling
319   the condition variable. Since the mutex is only released implicitly in
320   mysql_cond_wait(), the signaling happens at the right place. We
321   have a safe synchronization.
322 
323   === Co-work with the DBUG facility ===
324 
325   When running the MySQL test suite with the --debug command line
326   option, the Debug Sync Facility writes trace messages to the DBUG
327   trace. The following shell commands proved very useful in extracting
328   relevant information:
329 
330   egrep 'query:|debug_sync_exec:' mysql-test/var/log/mysqld.1.trace
331 
332   It shows all executed SQL statements and all actions executed by
333   synchronization points.
334 
335   Sometimes it is also useful to see, which synchronization points have
336   been run through (hit) with or without executing actions. Then add
337   "|debug_sync_point:" to the egrep pattern.
338 
339   === Further reading ===
340 
341   For a discussion of other methods to synchronize threads see
342   http://forge.mysql.com/wiki/MySQL_Internals_Test_Synchronization
343 
344   For complete syntax tests, functional tests, and examples see the test
345   case debug_sync.test.
346 
347   See also worklog entry WL#4259 - Test Synchronization Facility
348 */
349 
350 #include "debug_sync.h"
351 
352 #if defined(ENABLED_DEBUG_SYNC)
353 
354 #include "sql_parse.h"
355 #include "log.h"
356 
357 #include <set>
358 #include <string>
359 #include <boost/algorithm/string.hpp>
360 
361 using std::max;
362 using std::min;
363 
364 /*
365   Action to perform at a synchronization point.
366   NOTE: This structure is moved around in memory by realloc(), qsort(),
367         and memmove(). Do not add objects with non-trivial constuctors
368         or destructors, which might prevent moving of this structure
369         with these functions.
370 */
371 struct st_debug_sync_action
372 {
373   ulong         activation_count;       /* max(hit_limit, execute) */
374   ulong         hit_limit;              /* hits before kill query */
375   ulong         execute;                /* executes before self-clear */
376   ulong         timeout;                /* wait_for timeout */
377   String        signal;                 /* signal to emit */
378   String        wait_for;               /* signal to wait for */
379   String        sync_point;             /* sync point name */
380   bool          need_sort;              /* if new action, array needs sort */
381   bool          clear_event;            /* do not clear signal if false */
382 };
383 
384 /* Debug sync control. Referenced by THD. */
385 struct st_debug_sync_control
386 {
387   st_debug_sync_action  *ds_action;             /* array of actions */
388   uint                  ds_active;              /* # active actions */
389   uint                  ds_allocated;           /* # allocated actions */
390   ulonglong             dsp_hits;               /* statistics */
391   ulonglong             dsp_executed;           /* statistics */
392   ulonglong             dsp_max_active;         /* statistics */
393   /*
394     thd->proc_info points at unsynchronized memory.
395     It must not go away as long as the thread exists.
396   */
397   char                  ds_proc_info[80];       /* proc_info string */
398 };
399 
400 typedef std::set<std::string> signal_event_set;
401 
402 /**
403   Definitions for the debug sync facility.
404   1. Global set of signal names which are signalled.
405   2. Global condition variable for signaling and waiting.
406   3. Global mutex to synchronize access to the above.
407 */
408 struct st_debug_sync_globals
409 {
410   signal_event_set      ds_signal_set;          /* list of signals signalled */
411   mysql_cond_t          ds_cond;                /* condition variable */
412   mysql_mutex_t         ds_mutex;               /* mutex variable */
413   ulonglong             dsp_hits;               /* statistics */
414   ulonglong             dsp_executed;           /* statistics */
415   ulonglong             dsp_max_active;         /* statistics */
416 
st_debug_sync_globalsst_debug_sync_globals417   st_debug_sync_globals() : dsp_hits(0), dsp_executed(0), dsp_max_active(0) {}
418 private:
419   // Not implemented:
420   st_debug_sync_globals(const st_debug_sync_globals&);
421   st_debug_sync_globals &operator=(const st_debug_sync_globals&);
422 };
423 static st_debug_sync_globals debug_sync_global; /* All globals in one object */
424 
425 /**
426   Callback pointer for C files.
427 */
428 extern "C" void (*debug_sync_C_callback_ptr)(const char *, size_t);
429 
430 /**
431   Callbacks from C files.
432 */
433 C_MODE_START
434 static void debug_sync_C_callback(const char *, size_t);
435 static int debug_sync_qsort_cmp(const void *, const void *);
436 C_MODE_END
437 
438 /**
439   Callback for debug sync, to be used by C files. See thr_lock.c for example.
440 
441   @description
442 
443     We cannot place a sync point directly in C files (like those in mysys or
444     certain storage engines written mostly in C like MyISAM or Maria). Because
445     they are C code and do not know the
446     macro DEBUG_SYNC(thd, sync_point_name). The macro needs a 'thd' argument.
447     Hence it cannot be used in files outside of the sql/ directory.
448 
449     The workaround is to call back simple functions like this one from
450     non-sql/ files.
451 
452     We want to allow modules like thr_lock to be used without sql/ and
453     especially without Debug Sync. So we cannot just do a simple call
454     of the callback function. Instead we provide a global pointer in
455     the other file, which is to be set to the callback by Debug Sync.
456     If the pointer is not set, no call back will be done. If Debug
457     Sync sets the pointer to a callback function like this one, it will
458     be called. That way thr_lock.c does not have an undefined reference
459     to Debug Sync and can be used without it. Debug Sync, in contrast,
460     has an undefined reference to that pointer and thus requires
461     thr_lock to be linked too. But this is not a problem as it is part
462     of the MySQL server anyway.
463 
464   @note
465     The callback pointer in C files is set only if debug sync is
466     initialized. And this is done only if opt_debug_sync_timeout is set.
467 */
468 
debug_sync_C_callback(const char * sync_point_name,size_t name_len)469 static void debug_sync_C_callback(const char *sync_point_name,
470                                   size_t name_len)
471 {
472   if (unlikely(opt_debug_sync_timeout))
473     debug_sync(current_thd, sync_point_name, name_len);
474 }
475 
476 static PSI_memory_key key_debug_THD_debug_sync_control;
477 static PSI_memory_key key_debug_sync_action;
478 
479 #ifdef HAVE_PSI_INTERFACE
480 static PSI_mutex_key key_debug_sync_globals_ds_mutex;
481 
482 static PSI_mutex_info all_debug_sync_mutexes[]=
483 {
484   { &key_debug_sync_globals_ds_mutex, "DEBUG_SYNC::mutex", PSI_FLAG_GLOBAL}
485 };
486 
487 static PSI_cond_key key_debug_sync_globals_ds_cond;
488 
489 static PSI_cond_info all_debug_sync_conds[]=
490 {
491   { &key_debug_sync_globals_ds_cond, "DEBUG_SYNC::cond", PSI_FLAG_GLOBAL}
492 };
493 
494 static PSI_memory_info all_debug_sync_memory[]=
495 {
496   { &key_debug_THD_debug_sync_control, "THD::debug_sync_control", 0},
497   { &key_debug_sync_action, "debug_sync_control::debug_sync_action", 0}
498 };
499 
init_debug_sync_psi_keys(void)500 static void init_debug_sync_psi_keys(void)
501 {
502   const char* category= "sql";
503   int count;
504 
505   count= array_elements(all_debug_sync_mutexes);
506   mysql_mutex_register(category, all_debug_sync_mutexes, count);
507 
508   count= array_elements(all_debug_sync_conds);
509   mysql_cond_register(category, all_debug_sync_conds, count);
510 
511   count= array_elements(all_debug_sync_memory);
512   mysql_memory_register(category, all_debug_sync_memory, count);
513 }
514 #endif /* HAVE_PSI_INTERFACE */
515 
516 /**
517   Set the THD::proc_info without instrumentation.
518   This method is private to DEBUG_SYNC,
519   and on purpose avoid any use of:
520   - the SHOW PROFILE instrumentation
521   - the PERFORMANCE_SCHEMA instrumentation
522   so that using DEBUG_SYNC() in the server code
523   does not cause the instrumentations to record
524   spurious data.
525 */
526 static const char*
debug_sync_thd_proc_info(THD * thd,const char * info)527 debug_sync_thd_proc_info(THD *thd, const char* info)
528 {
529   const char* old_proc_info= thd->proc_info;
530   thd->proc_info= info;
531   return old_proc_info;
532 }
533 
534 /**
535   Initialize the debug sync facility at server start.
536 
537   @return status
538     @retval     0       ok
539     @retval     != 0    error
540 */
541 
debug_sync_init(void)542 int debug_sync_init(void)
543 {
544   DBUG_ENTER("debug_sync_init");
545 
546 #ifdef HAVE_PSI_INTERFACE
547   init_debug_sync_psi_keys();
548 #endif
549 
550   if (opt_debug_sync_timeout)
551   {
552     int rc;
553 
554     /* Initialize the global variables. */
555     if ((rc= mysql_cond_init(key_debug_sync_globals_ds_cond,
556                              &debug_sync_global.ds_cond)) ||
557         (rc= mysql_mutex_init(key_debug_sync_globals_ds_mutex,
558                               &debug_sync_global.ds_mutex,
559                               MY_MUTEX_INIT_FAST)))
560       DBUG_RETURN(rc); /* purecov: inspected */
561 
562     /* Set the call back pointer in C files. */
563     debug_sync_C_callback_ptr= debug_sync_C_callback;
564   }
565 
566   DBUG_RETURN(0);
567 }
568 
569 
570 /**
571   End the debug sync facility.
572 
573   @description
574     This is called at server shutdown or after a thread initialization error.
575 */
576 
debug_sync_end(void)577 void debug_sync_end(void)
578 {
579   DBUG_ENTER("debug_sync_end");
580 
581   /* End the facility only if it had been initialized. */
582   if (debug_sync_C_callback_ptr)
583   {
584     /* Clear the call back pointer in C files. */
585     debug_sync_C_callback_ptr= NULL;
586 
587     /* Destroy the global variables. */
588     debug_sync_global.ds_signal_set.clear();
589     mysql_cond_destroy(&debug_sync_global.ds_cond);
590     mysql_mutex_destroy(&debug_sync_global.ds_mutex);
591 
592     /* Print statistics. */
593     {
594       char llbuff[22];
595       sql_print_information("Debug sync points hit:                   %22s",
596                             llstr(debug_sync_global.dsp_hits, llbuff));
597       sql_print_information("Debug sync points executed:              %22s",
598                             llstr(debug_sync_global.dsp_executed, llbuff));
599       sql_print_information("Debug sync points max active per thread: %22s",
600                             llstr(debug_sync_global.dsp_max_active, llbuff));
601     }
602   }
603 
604   DBUG_VOID_RETURN;
605 }
606 
607 
608 /* purecov: begin tested */
609 
610 /**
611   Disable the facility after lack of memory if no error can be returned.
612 
613   @note
614     Do not end the facility here because the global variables can
615     be in use by other threads.
616 */
617 
debug_sync_emergency_disable(void)618 static void debug_sync_emergency_disable(void)
619 {
620   DBUG_ENTER("debug_sync_emergency_disable");
621 
622   opt_debug_sync_timeout= 0;
623 
624   DBUG_PRINT("debug_sync",
625              ("Debug Sync Facility disabled due to lack of memory."));
626   sql_print_error("Debug Sync Facility disabled due to lack of memory.");
627 
628   DBUG_VOID_RETURN;
629 }
630 
631 /* purecov: end */
632 
633 
634 /**
635   Initialize the debug sync facility at thread start.
636 
637   @param[in]    thd             thread handle
638 */
639 
debug_sync_init_thread(THD * thd)640 void debug_sync_init_thread(THD *thd)
641 {
642   DBUG_ENTER("debug_sync_init_thread");
643   assert(thd);
644 
645   if (opt_debug_sync_timeout)
646   {
647     thd->debug_sync_control= (st_debug_sync_control*)
648       my_malloc(key_debug_THD_debug_sync_control,
649                 sizeof(st_debug_sync_control), MYF(MY_WME | MY_ZEROFILL));
650     if (!thd->debug_sync_control)
651     {
652       /*
653         Error is reported by my_malloc().
654         We must disable the facility. We have no way to return an error.
655       */
656       debug_sync_emergency_disable(); /* purecov: tested */
657     }
658   }
659 
660   DBUG_VOID_RETURN;
661 }
662 
debug_sync_claim_memory_ownership(THD * thd)663 void debug_sync_claim_memory_ownership(THD *thd)
664 {
665   DBUG_ENTER("debug_sync_claim_memory_ownership");
666   assert(thd);
667 
668   st_debug_sync_control *ds_control= thd->debug_sync_control;
669 
670   if (ds_control != NULL)
671   {
672     if (ds_control->ds_action)
673     {
674       st_debug_sync_action *action= ds_control->ds_action;
675       st_debug_sync_action *action_end= action + ds_control->ds_allocated;
676       for (; action < action_end; action++)
677       {
678         action->signal.mem_claim();
679         action->wait_for.mem_claim();
680         action->sync_point.mem_claim();
681       }
682       my_claim(ds_control->ds_action);
683     }
684 
685     my_claim(ds_control);
686   }
687 
688   DBUG_VOID_RETURN;
689 }
690 
691 
692 /**
693   End the debug sync facility at thread end.
694 
695   @param[in]    thd             thread handle
696 */
697 
debug_sync_end_thread(THD * thd)698 void debug_sync_end_thread(THD *thd)
699 {
700   DBUG_ENTER("debug_sync_end_thread");
701   assert(thd);
702 
703   if (thd->debug_sync_control)
704   {
705     st_debug_sync_control *ds_control= thd->debug_sync_control;
706 
707     /*
708       This synchronization point can be used to synchronize on thread end.
709       This is the latest point in a THD's life, where this can be done.
710     */
711     DEBUG_SYNC(thd, "thread_end");
712 
713     if (ds_control->ds_action)
714     {
715       st_debug_sync_action *action= ds_control->ds_action;
716       st_debug_sync_action *action_end= action + ds_control->ds_allocated;
717       for (; action < action_end; action++)
718       {
719         action->signal.mem_free();
720         action->wait_for.mem_free();
721         action->sync_point.mem_free();
722       }
723       my_free(ds_control->ds_action);
724     }
725 
726     /* Statistics. */
727     mysql_mutex_lock(&debug_sync_global.ds_mutex);
728     debug_sync_global.dsp_hits+=           ds_control->dsp_hits;
729     debug_sync_global.dsp_executed+=       ds_control->dsp_executed;
730     if (debug_sync_global.dsp_max_active < ds_control->dsp_max_active)
731       debug_sync_global.dsp_max_active=    ds_control->dsp_max_active;
732     mysql_mutex_unlock(&debug_sync_global.ds_mutex);
733 
734     my_free(ds_control);
735     thd->debug_sync_control= NULL;
736   }
737 
738   DBUG_VOID_RETURN;
739 }
740 
741 
742 /**
743   Move a string by length.
744 
745   @param[out]   to              buffer for the resulting string
746   @param[in]    to_end          end of buffer
747   @param[in]    from            source string
748   @param[in]    length          number of bytes to copy
749 
750   @return       pointer to end of copied string
751 */
752 
debug_sync_bmove_len(char * to,char * to_end,const char * from,size_t length)753 static char *debug_sync_bmove_len(char *to, char *to_end,
754                                   const char *from, size_t length)
755 {
756   assert(to);
757   assert(to_end);
758   assert(!length || from);
759   set_if_smaller(length, (size_t) (to_end - to));
760   memcpy(to, from, length);
761   return (to + length);
762 }
763 
764 
765 #if !defined(NDEBUG)
766 
767 /**
768   Create a string that describes an action.
769 
770   @param[out]   result          buffer for the resulting string
771   @param[in]    size            size of result buffer
772   @param[in]    action          action to describe
773 */
774 
debug_sync_action_string(char * result,uint size,st_debug_sync_action * action)775 static void debug_sync_action_string(char *result, uint size,
776                                      st_debug_sync_action *action)
777 {
778   char  *wtxt= result;
779   char  *wend= wtxt + size - 1; /* Allow emergency '\0'. */
780   assert(result);
781   assert(action);
782 
783   /* If an execute count is present, signal or wait_for are needed too. */
784   assert(!action->execute ||
785          action->signal.length() || action->wait_for.length());
786 
787   if (action->execute)
788   {
789     if (action->signal.length())
790     {
791       wtxt= debug_sync_bmove_len(wtxt, wend, STRING_WITH_LEN("SIGNAL "));
792       wtxt= debug_sync_bmove_len(wtxt, wend, action->signal.ptr(),
793                                  action->signal.length());
794     }
795     if (action->wait_for.length())
796     {
797       if ((wtxt == result) && (wtxt < wend))
798         *(wtxt++)= ' ';
799       wtxt= debug_sync_bmove_len(wtxt, wend, STRING_WITH_LEN(" WAIT_FOR "));
800       wtxt= debug_sync_bmove_len(wtxt, wend, action->wait_for.ptr(),
801                                  action->wait_for.length());
802 
803       if (action->timeout != opt_debug_sync_timeout)
804       {
805         wtxt+= my_snprintf(wtxt, wend - wtxt, " TIMEOUT %lu", action->timeout);
806       }
807     }
808     if (action->execute != 1)
809     {
810       wtxt+= my_snprintf(wtxt, wend - wtxt, " EXECUTE %lu", action->execute);
811     }
812   }
813   if (action->hit_limit)
814   {
815     wtxt+= my_snprintf(wtxt, wend - wtxt, "%sHIT_LIMIT %lu",
816                        (wtxt == result) ? "" : " ", action->hit_limit);
817   }
818 
819   /*
820     If (wtxt == wend) string may not be terminated.
821     There is one byte left for an emergency termination.
822   */
823   *wtxt= '\0';
824 }
825 
826 
827 /**
828   Print actions.
829 
830   @param[in]    thd             thread handle
831 */
832 
debug_sync_print_actions(THD * thd)833 static void debug_sync_print_actions(THD *thd)
834 {
835   st_debug_sync_control *ds_control= thd->debug_sync_control;
836   uint                  idx;
837   DBUG_ENTER("debug_sync_print_actions");
838   assert(thd);
839 
840   if (!ds_control)
841     DBUG_VOID_RETURN;
842 
843   for (idx= 0; idx < ds_control->ds_active; idx++)
844   {
845     const char *dsp_name= ds_control->ds_action[idx].sync_point.c_ptr();
846     char action_string[256];
847 
848     debug_sync_action_string(action_string, sizeof(action_string),
849                              ds_control->ds_action + idx);
850     DBUG_PRINT("debug_sync_list", ("%s %s", dsp_name, action_string));
851   }
852 
853   DBUG_VOID_RETURN;
854 }
855 
856 #endif /* !defined(NDEBUG) */
857 
858 
859 /**
860   Compare two actions by sync point name length, string.
861 
862   @param[in]    arg1            reference to action1
863   @param[in]    arg2            reference to action2
864 
865   @return       difference
866     @retval     == 0            length1/string1 is same as length2/string2
867     @retval     < 0             length1/string1 is smaller
868     @retval     > 0             length1/string1 is bigger
869 */
870 
debug_sync_qsort_cmp(const void * arg1,const void * arg2)871 static int debug_sync_qsort_cmp(const void* arg1, const void* arg2)
872 {
873   st_debug_sync_action *action1= (st_debug_sync_action*) arg1;
874   st_debug_sync_action *action2= (st_debug_sync_action*) arg2;
875   int diff;
876   assert(action1);
877   assert(action2);
878 
879   if (!(diff= static_cast<int>(action1->sync_point.length() - action2->sync_point.length())))
880     diff= memcmp(action1->sync_point.ptr(), action2->sync_point.ptr(),
881                  action1->sync_point.length());
882 
883   return diff;
884 }
885 
886 
887 /**
888   Find a debug sync action.
889 
890   @param[in]    actionarr       array of debug sync actions
891   @param[in]    quantity        number of actions in array
892   @param[in]    dsp_name        name of debug sync point to find
893   @param[in]    name_len        length of name of debug sync point
894 
895   @return       action
896     @retval     != NULL         found sync point in array
897     @retval     NULL            not found
898 
899   @description
900     Binary search. Array needs to be sorted by length, sync point name.
901 */
902 
debug_sync_find(st_debug_sync_action * actionarr,int quantity,const char * dsp_name,size_t name_len)903 static st_debug_sync_action *debug_sync_find(st_debug_sync_action *actionarr,
904                                              int quantity,
905                                              const char *dsp_name,
906                                              size_t name_len)
907 {
908   st_debug_sync_action  *action;
909   int                   low ;
910   int                   high ;
911   int                   mid ;
912   int                   diff ;
913   assert(actionarr);
914   assert(dsp_name);
915   assert(name_len);
916 
917   low= 0;
918   high= quantity;
919 
920   while (low < high)
921   {
922     mid= (low + high) / 2;
923     action= actionarr + mid;
924     if (!(diff= static_cast<int>(name_len - action->sync_point.length())) &&
925         !(diff= memcmp(dsp_name, action->sync_point.ptr(), name_len)))
926       return action;
927     if (diff > 0)
928       low= mid + 1;
929     else
930       high= mid - 1;
931   }
932 
933   if (low < quantity)
934   {
935     action= actionarr + low;
936     if ((name_len == action->sync_point.length()) &&
937         !memcmp(dsp_name, action->sync_point.ptr(), name_len))
938       return action;
939   }
940 
941   return NULL;
942 }
943 
944 
945 /**
946   Reset the debug sync facility.
947 
948   @param[in]    thd             thread handle
949 
950   @description
951     Remove all actions of this thread.
952     Clear the global signal.
953 */
954 
debug_sync_reset(THD * thd)955 static void debug_sync_reset(THD *thd)
956 {
957   st_debug_sync_control *ds_control= thd->debug_sync_control;
958   DBUG_ENTER("debug_sync_reset");
959   assert(thd);
960   assert(ds_control);
961 
962   /* Remove all actions of this thread. */
963   ds_control->ds_active= 0;
964 
965   /* Clear the signals. */
966   mysql_mutex_lock(&debug_sync_global.ds_mutex);
967   debug_sync_global.ds_signal_set.clear();
968   mysql_mutex_unlock(&debug_sync_global.ds_mutex);
969 
970   DBUG_VOID_RETURN;
971 }
972 
973 
974 /**
975   Remove a debug sync action.
976 
977   @param[in]    ds_control      control object
978   @param[in]    action          action to be removed
979 
980   @description
981     Removing an action mainly means to decrement the ds_active counter.
982     But if the action is between other active action in the array, then
983     the array needs to be shrinked. The active actions above the one to
984     be removed have to be moved down by one slot.
985 */
986 
debug_sync_remove_action(st_debug_sync_control * ds_control,st_debug_sync_action * action)987 static void debug_sync_remove_action(st_debug_sync_control *ds_control,
988                                      st_debug_sync_action *action)
989 {
990   uint dsp_idx= static_cast<uint>(action - ds_control->ds_action);
991   DBUG_ENTER("debug_sync_remove_action");
992   assert(ds_control);
993   assert(ds_control == current_thd->debug_sync_control);
994   assert(action);
995   assert(dsp_idx < ds_control->ds_active);
996 
997   /* Decrement the number of currently active actions. */
998   ds_control->ds_active--;
999 
1000   /*
1001     If this was not the last active action in the array, we need to
1002     shift remaining active actions down to keep the array gap-free.
1003     Otherwise binary search might fail or take longer than necessary at
1004     least. Also new actions are always put to the end of the array.
1005   */
1006   if (ds_control->ds_active > dsp_idx)
1007   {
1008     /*
1009       Do not make save_action an object of class st_debug_sync_action.
1010       Its destructor would tamper with the String pointers.
1011     */
1012     uchar save_action[sizeof(st_debug_sync_action)];
1013 
1014     /*
1015       Copy the to-be-removed action object to temporary storage before
1016       the shift copies the string pointers over. Do not use assignment
1017       because it would use assignment operator methods for the Strings.
1018       This would copy the strings. The shift below overwrite the string
1019       pointers without freeing them first. By using memmove() we save
1020       the pointers, which are overwritten by the shift.
1021     */
1022     memmove(save_action, action, sizeof(st_debug_sync_action));
1023 
1024     /* Move actions down. */
1025     void *dest= ds_control->ds_action + dsp_idx;
1026     const void *src= ds_control->ds_action + dsp_idx + 1;
1027     memmove(dest, src,
1028             (ds_control->ds_active - dsp_idx) *
1029             sizeof(st_debug_sync_action));
1030 
1031     /*
1032       Copy back the saved action object to the now free array slot. This
1033       replaces the double references of String pointers that have been
1034       produced by the shift. Again do not use an assignment operator to
1035       avoid string allocation/copy.
1036     */
1037     dest= ds_control->ds_action + ds_control->ds_active;
1038     memmove(dest, save_action,
1039             sizeof(st_debug_sync_action));
1040   }
1041 
1042   DBUG_VOID_RETURN;
1043 }
1044 
1045 
1046 /**
1047   Get a debug sync action.
1048 
1049   @param[in]    thd             thread handle
1050   @param[in]    dsp_name        debug sync point name
1051   @param[in]    name_len        length of sync point name
1052 
1053   @return       action
1054     @retval     != NULL         ok
1055     @retval     NULL            error
1056 
1057   @description
1058     Find the debug sync action for a debug sync point or make a new one.
1059 */
1060 
debug_sync_get_action(THD * thd,const char * dsp_name,size_t name_len)1061 static st_debug_sync_action *debug_sync_get_action(THD *thd,
1062                                                    const char *dsp_name,
1063                                                    size_t name_len)
1064 {
1065   st_debug_sync_control *ds_control= thd->debug_sync_control;
1066   st_debug_sync_action  *action;
1067   DBUG_ENTER("debug_sync_get_action");
1068   assert(thd);
1069   assert(dsp_name);
1070   assert(name_len);
1071   assert(ds_control);
1072   DBUG_PRINT("debug_sync", ("sync_point: '%.*s'", (int) name_len, dsp_name));
1073   DBUG_PRINT("debug_sync", ("active: %u  allocated: %u",
1074                             ds_control->ds_active, ds_control->ds_allocated));
1075 
1076   /* There cannot be more active actions than allocated. */
1077   assert(ds_control->ds_active <= ds_control->ds_allocated);
1078   /* If there are active actions, the action array must be present. */
1079   assert(!ds_control->ds_active || ds_control->ds_action);
1080 
1081   /* Try to reuse existing action if there is one for this sync point. */
1082   if (ds_control->ds_active &&
1083       (action= debug_sync_find(ds_control->ds_action, ds_control->ds_active,
1084                                dsp_name, name_len)))
1085   {
1086     /* Reuse an already active sync point action. */
1087     assert((uint)(action - ds_control->ds_action) < ds_control->ds_active);
1088     DBUG_PRINT("debug_sync", ("reuse action idx: %ld",
1089                               (long) (action - ds_control->ds_action)));
1090   }
1091   else
1092   {
1093     /* Create a new action. */
1094     int dsp_idx= ds_control->ds_active++;
1095     set_if_bigger(ds_control->dsp_max_active, ds_control->ds_active);
1096     if (ds_control->ds_active > ds_control->ds_allocated)
1097     {
1098       uint new_alloc= ds_control->ds_active + 3;
1099       void *new_action= my_realloc(key_debug_sync_action,
1100                                    ds_control->ds_action,
1101                                    new_alloc * sizeof(st_debug_sync_action),
1102                                    MYF(MY_WME | MY_ALLOW_ZERO_PTR));
1103       if (!new_action)
1104       {
1105         /* Error is reported by my_malloc(). */
1106         goto err; /* purecov: tested */
1107       }
1108       ds_control->ds_action= (st_debug_sync_action*) new_action;
1109       ds_control->ds_allocated= new_alloc;
1110       /* Clear memory as we do not run string constructors here. */
1111       void *dest= (ds_control->ds_action + dsp_idx);
1112       memset(dest, 0,
1113             (new_alloc - dsp_idx) * sizeof(st_debug_sync_action));
1114     }
1115     DBUG_PRINT("debug_sync", ("added action idx: %u", dsp_idx));
1116     action= ds_control->ds_action + dsp_idx;
1117     if (action->sync_point.copy(dsp_name, name_len, system_charset_info))
1118     {
1119       /* Error is reported by my_malloc(). */
1120       goto err; /* purecov: tested */
1121     }
1122     action->need_sort= TRUE;
1123   }
1124   assert(action >= ds_control->ds_action);
1125   assert(action < ds_control->ds_action + ds_control->ds_active);
1126   DBUG_PRINT("debug_sync", ("action: 0x%lx  array: 0x%lx  count: %u",
1127                             (long) action, (long) ds_control->ds_action,
1128                             ds_control->ds_active));
1129 
1130   DBUG_RETURN(action);
1131 
1132   /* purecov: begin tested */
1133  err:
1134   DBUG_RETURN(NULL);
1135   /* purecov: end */
1136 }
1137 
1138 
1139 /**
1140   Set a debug sync action.
1141 
1142   @param[in]    thd             thread handle
1143   @param[in]    action          synchronization action
1144 
1145   @return       status
1146     @retval     FALSE           ok
1147     @retval     TRUE            error
1148 
1149   @description
1150     This is called from the debug sync parser. It arms the action for
1151     the requested sync point. If the action parsed into an empty action,
1152     it is removed instead.
1153 
1154     Setting an action for a sync point means to make the sync point
1155     active. When it is hit it will execute this action.
1156 
1157     Before parsing, we "get" an action object. This is placed at the
1158     end of the thread's action array unless the requested sync point
1159     has an action already.
1160 
1161     Then the parser fills the action object from the request string.
1162 
1163     Finally the action is "set" for the sync point. If it was parsed
1164     to be empty, it is removed from the array. If it did belong to a
1165     sync point before, the sync point becomes inactive. If the action
1166     became non-empty and it did not belong to a sync point before (it
1167     was added at the end of the action array), the action array needs
1168     to be sorted by sync point.
1169 
1170     If the sync point name is "now", it is executed immediately.
1171 */
1172 
debug_sync_set_action(THD * thd,st_debug_sync_action * action)1173 static bool debug_sync_set_action(THD *thd, st_debug_sync_action *action)
1174 {
1175   st_debug_sync_control *ds_control= thd->debug_sync_control;
1176   bool is_dsp_now= FALSE;
1177   DBUG_ENTER("debug_sync_set_action");
1178   assert(thd);
1179   assert(action);
1180   assert(ds_control);
1181 
1182   action->activation_count= max(action->hit_limit, action->execute);
1183   if (!action->activation_count)
1184   {
1185     debug_sync_remove_action(ds_control, action);
1186     DBUG_PRINT("debug_sync", ("action cleared"));
1187   }
1188   else
1189   {
1190     const char *dsp_name= action->sync_point.c_ptr();
1191     DBUG_EXECUTE("debug_sync", {
1192         /* Functions as DBUG_PRINT args can change keyword and line nr. */
1193         const char *sig_emit= action->signal.c_ptr();
1194         const char *sig_wait= action->wait_for.c_ptr();
1195         DBUG_PRINT("debug_sync",
1196                    ("sync_point: '%s'  activation_count: %lu  hit_limit: %lu  "
1197                     "execute: %lu  timeout: %lu  signal: '%s'  wait_for: '%s'",
1198                     dsp_name, action->activation_count,
1199                     action->hit_limit, action->execute, action->timeout,
1200                     sig_emit, sig_wait));});
1201 
1202     /* Check this before sorting the array. action may move. */
1203     is_dsp_now= !my_strcasecmp(system_charset_info, dsp_name, "now");
1204 
1205     if (action->need_sort)
1206     {
1207       action->need_sort= FALSE;
1208       /* Sort actions by (name_len, name). */
1209       my_qsort(ds_control->ds_action, ds_control->ds_active,
1210                sizeof(st_debug_sync_action), debug_sync_qsort_cmp);
1211     }
1212   }
1213   DBUG_EXECUTE("debug_sync_list", debug_sync_print_actions(thd););
1214 
1215   /* Execute the special sync point 'now' if activated above. */
1216   if (is_dsp_now)
1217   {
1218     DEBUG_SYNC(thd, "now");
1219     /*
1220       If HIT_LIMIT for sync point "now" was 1, the execution of the sync
1221       point decremented it to 0. In this case the following happened:
1222 
1223       - an error message was reported with my_error() and
1224       - the statement was killed with thd->killed= THD::KILL_QUERY.
1225 
1226       If a statement reports an error, it must not call send_ok().
1227       The calling functions will not call send_ok(), if we return TRUE
1228       from this function.
1229 
1230       thd->killed is also set if the wait is interrupted from a
1231       KILL or KILL QUERY statement. In this case, no error is reported
1232       and shall not be reported as a result of SET DEBUG_SYNC.
1233       Hence, we check for the first condition above.
1234     */
1235     if (thd->is_error())
1236       DBUG_RETURN(TRUE);
1237   }
1238 
1239   DBUG_RETURN(FALSE);
1240 }
1241 
1242 
1243 /*
1244   Advance the pointer by length of multi-byte character.
1245 
1246     @param    ptr   pointer to multibyte character.
1247 
1248     @return   NULL or pointer after advancing pointer by the
1249               length of multi-byte character pointed to.
1250 */
1251 
advance_mbchar_ptr(const char * ptr)1252 static inline const char *advance_mbchar_ptr(const char *ptr)
1253 {
1254   uint clen= my_mbcharlen(system_charset_info, (uchar) *ptr);
1255 
1256   return (clen != 0) ? ptr + clen : NULL;
1257 }
1258 
1259 
1260 /*
1261   Skip whitespace characters from the beginning of the multi-byte string.
1262 
1263   @param    ptr     pointer to the multi-byte string.
1264 
1265   @return   a pointer to the first non-whitespace character or NULL if the
1266             string consists from whitespace characters only.
1267 */
1268 
skip_whitespace(const char * ptr)1269 static inline const char *skip_whitespace(const char *ptr)
1270 {
1271   while (ptr != NULL && *ptr && my_isspace(system_charset_info, *ptr))
1272     ptr= advance_mbchar_ptr(ptr);
1273 
1274   return ptr;
1275 }
1276 
1277 
1278 /*
1279   Get pointer to end of token.
1280 
1281   @param    ptr  pointer to start of token
1282 
1283   @return   NULL or pointer to end of token.
1284 */
1285 
get_token_end_ptr(const char * ptr)1286 static inline const char *get_token_end_ptr(const char *ptr)
1287 {
1288   while (ptr != NULL && *ptr && !my_isspace(system_charset_info, *ptr))
1289     ptr= advance_mbchar_ptr(ptr);
1290 
1291   return ptr;
1292 }
1293 
1294 
1295 /**
1296   Extract a token from a string.
1297 
1298   @param[out]     token_p         returns start of token
1299   @param[out]     token_length_p  returns length of token
1300   @param[in,out]  ptr             current string pointer, adds '\0' terminators
1301 
1302   @return       string pointer or NULL
1303     @retval     != NULL         ptr behind token terminator or at string end
1304     @retval     NULL            no token found in remainder of string
1305 
1306   @note
1307     This function assumes that the string is in system_charset_info,
1308     that this charset is single byte for ASCII NUL ('\0'), that no
1309     character except of ASCII NUL ('\0') contains a byte with value 0,
1310     and that ASCII NUL ('\0') is used as the string terminator.
1311 
1312     This function needs to return tokens that are terminated with ASCII
1313     NUL ('\0'). The tokens are used in my_strcasecmp(). Unfortunately
1314     there is no my_strncasecmp().
1315 
1316     To return the last token without copying it, we require the input
1317     string to be nul terminated.
1318 
1319   @description
1320     This function skips space characters at string begin.
1321 
1322     It returns a pointer to the first non-space character in *token_p.
1323 
1324     If no non-space character is found before the string terminator
1325     ASCII NUL ('\0'), the function returns NULL. *token_p and
1326     *token_length_p remain unchanged in this case (they are not set).
1327 
1328     The function takes a space character or an ASCII NUL ('\0') as a
1329     terminator of the token. The space character could be multi-byte.
1330 
1331     It returns the length of the token in bytes, excluding the
1332     terminator, in *token_length_p.
1333 
1334     If the terminator of the token is ASCII NUL ('\0'), it returns a
1335     pointer to the terminator (string end).
1336 
1337     If the terminator is a space character, it replaces the the first
1338     byte of the terminator character by ASCII NUL ('\0'), skips the (now
1339     corrupted) terminator character, and skips all following space
1340     characters. It returns a pointer to the next non-space character or
1341     to the string terminator ASCII NUL ('\0').
1342 */
1343 
debug_sync_token(char ** token_p,size_t * token_length_p,char * ptr)1344 static char *debug_sync_token(char **token_p, size_t *token_length_p, char *ptr)
1345 {
1346   assert(token_p);
1347   assert(token_length_p);
1348   assert(ptr);
1349 
1350 
1351   /* Skip leading space */
1352   ptr= const_cast<char*>(skip_whitespace(ptr));
1353 
1354   if (ptr == NULL || !*ptr)
1355     return NULL;
1356 
1357   /* Get token start. */
1358   *token_p= ptr;
1359 
1360   /* Find token end. */
1361   ptr= const_cast<char*>(get_token_end_ptr(ptr));
1362 
1363   if (ptr == NULL)
1364     return NULL;
1365 
1366   /* Get token length. */
1367   *token_length_p= ptr - *token_p;
1368 
1369   /* If necessary, terminate token. */
1370   if (*ptr)
1371   {
1372      char* tmp= ptr;
1373 
1374     /* Advance by terminator character length. */
1375     ptr= const_cast<char*>(advance_mbchar_ptr(ptr));
1376     if (ptr != NULL)
1377     {
1378       /* Terminate token. */
1379       *tmp= '\0';
1380 
1381       /* Skip trailing space */
1382       ptr= const_cast<char*>(skip_whitespace(ptr));
1383     }
1384   }
1385   return ptr;
1386 }
1387 
1388 
1389 /**
1390   Extract a number from a string.
1391 
1392   @param[out]   number_p        returns number
1393   @param[in]    actstrptr       current pointer in action string
1394 
1395   @return       string pointer or NULL
1396     @retval     != NULL         ptr behind token terminator or at string end
1397     @retval     NULL            no token found or token is not valid number
1398 
1399   @note
1400     The same assumptions about charset apply as for debug_sync_token().
1401 
1402   @description
1403     This function fetches a token from the string and converts it
1404     into a number.
1405 
1406     If there is no token left in the string, or the token is not a valid
1407     decimal number, NULL is returned. The result in *number_p is
1408     undefined in this case.
1409 */
1410 
debug_sync_number(ulong * number_p,char * actstrptr)1411 static char *debug_sync_number(ulong *number_p, char *actstrptr)
1412 {
1413   char                  *ptr;
1414   char                  *ept;
1415   char                  *token;
1416   size_t                token_length;
1417   assert(number_p);
1418   assert(actstrptr);
1419 
1420   /* Get token from string. */
1421   if (!(ptr= debug_sync_token(&token, &token_length, actstrptr)))
1422     goto end;
1423 
1424   *number_p= strtoul(token, &ept, 10);
1425   if (*ept)
1426     ptr= NULL;
1427 
1428  end:
1429   return ptr;
1430 }
1431 
1432 
1433 /**
1434   Evaluate a debug sync action string.
1435 
1436   @param[in]        thd             thread handle
1437   @param[in,out]    action_str      action string to receive '\0' terminators
1438 
1439   @return           status
1440     @retval         FALSE           ok
1441     @retval         TRUE            error
1442 
1443   @description
1444     This is called when the DEBUG_SYNC system variable is set.
1445     Parse action string, build a debug sync action, activate it.
1446 
1447     Before parsing, we "get" an action object. This is placed at the
1448     end of the thread's action array unless the requested sync point
1449     has an action already.
1450 
1451     Then the parser fills the action object from the request string.
1452 
1453     Finally the action is "set" for the sync point. This means that the
1454     sync point becomes active or inactive, depending on the action
1455     values.
1456 
1457   @note
1458     The input string needs to be ASCII NUL ('\0') terminated. We split
1459     nul-terminated tokens in it without copy.
1460 
1461   @see the function comment of debug_sync_token() for more constraints
1462     for the string.
1463 */
1464 
debug_sync_eval_action(THD * thd,char * action_str)1465 static bool debug_sync_eval_action(THD *thd, char *action_str)
1466 {
1467   st_debug_sync_action  *action= NULL;
1468   const char            *errmsg;
1469   char                  *ptr;
1470   char                  *token;
1471   size_t                token_length= 0;
1472   DBUG_ENTER("debug_sync_eval_action");
1473   assert(thd);
1474   assert(action_str);
1475 
1476   /*
1477     Get debug sync point name. Or a special command.
1478   */
1479   if (!(ptr= debug_sync_token(&token, &token_length, action_str)))
1480   {
1481     errmsg= "Missing synchronization point name";
1482     goto err;
1483   }
1484 
1485   /*
1486     If there is a second token, the first one is the sync point name.
1487   */
1488   if (*ptr)
1489   {
1490     /* Get an action object to collect the requested action parameters. */
1491     action= debug_sync_get_action(thd, token, token_length);
1492     if (!action)
1493     {
1494       /* Error message is sent. */
1495       DBUG_RETURN(TRUE); /* purecov: tested */
1496     }
1497   }
1498 
1499   /*
1500     Get kind of action to be taken at sync point.
1501   */
1502   if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1503   {
1504     /* No action present. Try special commands. Token unchanged. */
1505 
1506     /*
1507       Try RESET.
1508     */
1509     if (!my_strcasecmp(system_charset_info, token, "RESET"))
1510     {
1511       /* It is RESET. Reset all actions and global signal. */
1512       debug_sync_reset(thd);
1513       goto end;
1514     }
1515 
1516     /* Token unchanged. It still contains sync point name. */
1517     errmsg= "Missing action after synchronization point name '%.*s'";
1518     goto err;
1519   }
1520 
1521   /*
1522     Check for pseudo actions first. Start with actions that work on
1523     an existing action.
1524   */
1525   assert(action);
1526 
1527   /*
1528     Try TEST.
1529   */
1530   if (!my_strcasecmp(system_charset_info, token, "TEST"))
1531   {
1532     /* It is TEST. Nothing must follow it. */
1533     if (*ptr)
1534     {
1535       errmsg= "Nothing must follow action TEST";
1536       goto err;
1537     }
1538 
1539     /* Execute sync point. */
1540     debug_sync(thd, action->sync_point.ptr(), action->sync_point.length());
1541     /* Fix statistics. This was not a real hit of the sync point. */
1542     thd->debug_sync_control->dsp_hits--;
1543     goto end;
1544   }
1545 
1546   /*
1547     Now check for actions that define a new action.
1548     Initialize action. Do not use memset(). Strings may have malloced.
1549   */
1550   action->activation_count= 0;
1551   action->hit_limit= 0;
1552   action->execute= 0;
1553   action->timeout= 0;
1554   action->signal.length(0);
1555   action->wait_for.length(0);
1556 
1557   /*
1558     Try CLEAR.
1559   */
1560   if (!my_strcasecmp(system_charset_info, token, "CLEAR"))
1561   {
1562     /* It is CLEAR. Nothing must follow it. */
1563     if (*ptr)
1564     {
1565       errmsg= "Nothing must follow action CLEAR";
1566       goto err;
1567     }
1568 
1569     /* Set (clear/remove) action. */
1570     goto set_action;
1571   }
1572 
1573   /*
1574     Now check for real sync point actions.
1575   */
1576 
1577   /*
1578     Try SIGNAL.
1579   */
1580   if (!my_strcasecmp(system_charset_info, token, "SIGNAL"))
1581   {
1582     /* It is SIGNAL. Signal name must follow. */
1583     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1584     {
1585       errmsg= "Missing signal name after action SIGNAL";
1586       goto err;
1587     }
1588     if (action->signal.copy(token, token_length, system_charset_info))
1589     {
1590       /* Error is reported by my_malloc(). */
1591       /* purecov: begin tested */
1592       errmsg= NULL;
1593       goto err;
1594       /* purecov: end */
1595     }
1596 
1597     /* Set default for EXECUTE option. */
1598     action->execute= 1;
1599 
1600     /* Get next token. If none follows, set action. */
1601     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1602       goto set_action;
1603   }
1604 
1605   /*
1606     Try WAIT_FOR.
1607   */
1608   if (!my_strcasecmp(system_charset_info, token, "WAIT_FOR"))
1609   {
1610     /* It is WAIT_FOR. Wait_for signal name must follow. */
1611     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1612     {
1613       errmsg= "Missing signal name after action WAIT_FOR";
1614       goto err;
1615     }
1616     if (action->wait_for.copy(token, token_length, system_charset_info))
1617     {
1618       /* Error is reported by my_malloc(). */
1619       /* purecov: begin tested */
1620       errmsg= NULL;
1621       goto err;
1622       /* purecov: end */
1623     }
1624 
1625     /* Set default for EXECUTE and TIMEOUT options. */
1626     action->execute= 1;
1627     action->timeout= opt_debug_sync_timeout;
1628     action->clear_event= true;
1629 
1630     /* Get next token. If none follows, set action. */
1631     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1632       goto set_action;
1633 
1634     /*
1635       Try TIMEOUT.
1636     */
1637     if (!my_strcasecmp(system_charset_info, token, "TIMEOUT"))
1638     {
1639       /* It is TIMEOUT. Number must follow. */
1640       if (!(ptr= debug_sync_number(&action->timeout, ptr)))
1641       {
1642         errmsg= "Missing valid number after TIMEOUT";
1643         goto err;
1644       }
1645 
1646       /* Get next token. If none follows, set action. */
1647       if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1648         goto set_action;
1649     }
1650   }
1651 
1652   /*
1653     Try EXECUTE.
1654   */
1655   if (!my_strcasecmp(system_charset_info, token, "EXECUTE"))
1656   {
1657     /*
1658       EXECUTE requires either SIGNAL and/or WAIT_FOR to be present.
1659       In this case action->execute has been preset to 1.
1660     */
1661     if (!action->execute)
1662     {
1663       errmsg= "Missing action before EXECUTE";
1664       goto err;
1665     }
1666 
1667     /* Number must follow. */
1668     if (!(ptr= debug_sync_number(&action->execute, ptr)))
1669     {
1670       errmsg= "Missing valid number after EXECUTE";
1671       goto err;
1672     }
1673 
1674     /* Get next token. If none follows, set action. */
1675     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1676       goto set_action;
1677   }
1678 
1679   /*
1680     Try NO_CLEAR_EVENT.
1681   */
1682   if (!my_strcasecmp(system_charset_info, token, "NO_CLEAR_EVENT"))
1683   {
1684     action->clear_event= false;
1685     /* Get next token. If none follows, set action. */
1686     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1687       goto set_action;
1688   }
1689 
1690   /*
1691     Try HIT_LIMIT.
1692   */
1693   if (!my_strcasecmp(system_charset_info, token, "HIT_LIMIT"))
1694   {
1695     /* Number must follow. */
1696     if (!(ptr= debug_sync_number(&action->hit_limit, ptr)))
1697     {
1698       errmsg= "Missing valid number after HIT_LIMIT";
1699       goto err;
1700     }
1701 
1702     /* Get next token. If none follows, set action. */
1703     if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
1704       goto set_action;
1705   }
1706 
1707   errmsg= "Illegal or out of order stuff: '%.*s'";
1708 
1709  err:
1710   if (errmsg)
1711   {
1712     /*
1713       NOTE: errmsg must either have %.*s or none % at all.
1714       It can be NULL if an error message is already reported
1715       (e.g. by my_malloc()).
1716     */
1717     set_if_smaller(token_length, 64); /* Limit error message length. */
1718     my_printf_error(ER_PARSE_ERROR, errmsg, MYF(0), token_length, token);
1719   }
1720   if (action)
1721     debug_sync_remove_action(thd->debug_sync_control, action);
1722   DBUG_RETURN(TRUE);
1723 
1724  set_action:
1725   DBUG_RETURN(debug_sync_set_action(thd, action));
1726 
1727  end:
1728   DBUG_RETURN(FALSE);
1729 }
1730 
1731 /**
1732   Set the system variable 'debug_sync'.
1733 
1734   @param[in]    thd             thread handle
1735   @param[in]    var             set variable request
1736 
1737   @return       status
1738     @retval     FALSE           ok, variable is set
1739     @retval     TRUE            error, variable could not be set
1740 
1741   @note
1742     "Setting" of the system variable 'debug_sync' does not mean to
1743     assign a value to it as usual. Instead a debug sync action is parsed
1744     from the input string and stored apart from the variable value.
1745 
1746   @note
1747     For efficiency reasons, the action string parser places '\0'
1748     terminators in the string. So we need to take a copy here.
1749 */
1750 
debug_sync_update(THD * thd,char * val_str)1751 bool debug_sync_update(THD *thd, char *val_str)
1752 {
1753   DBUG_ENTER("debug_sync_update");
1754   DBUG_PRINT("debug_sync", ("set action: '%s'", val_str));
1755 
1756   /*
1757     debug_sync_eval_action() places '\0' in the string, which itself
1758     must be '\0' terminated.
1759   */
1760   DBUG_RETURN(opt_debug_sync_timeout ?
1761               debug_sync_eval_action(thd, val_str) :
1762               FALSE);
1763 }
1764 
1765 
1766 /**
1767   Retrieve the value of the system variable 'debug_sync'.
1768 
1769   @param[in]    thd             thread handle
1770 
1771   @return       string
1772     @retval     != NULL         ok, string pointer
1773     @retval     NULL            memory allocation error
1774 
1775   @note
1776     The value of the system variable 'debug_sync' reflects if
1777     the facility is enabled ("ON") or disabled (default, "OFF").
1778 
1779     When "ON", the list of signals signalled are added separated by comma.
1780 */
1781 
debug_sync_value_ptr(THD * thd)1782 uchar *debug_sync_value_ptr(THD *thd)
1783 {
1784   char *value;
1785   DBUG_ENTER("debug_sync_value_ptr");
1786 
1787   if (opt_debug_sync_timeout)
1788   {
1789     std::string signals_on("ON - signals: '");
1790     static char sep[]= ",";
1791 
1792     // Ensure exclusive access to debug_sync_global.ds_signal_set
1793     mysql_mutex_lock(&debug_sync_global.ds_mutex);
1794 
1795     signal_event_set::const_iterator iter;
1796     for (iter= debug_sync_global.ds_signal_set.begin();
1797          iter != debug_sync_global.ds_signal_set.end(); )
1798     {
1799       signals_on.append(*iter);
1800       if ((++iter) != debug_sync_global.ds_signal_set.end())
1801         signals_on.append(sep);
1802     }
1803     signals_on.append("'");
1804 
1805     const char *c_str= signals_on.c_str();
1806     const size_t lgt= strlen(c_str) + 1;
1807 
1808     if ((value= (char*) alloc_root(thd->mem_root, lgt)))
1809       memcpy(value, c_str, lgt);
1810 
1811     mysql_mutex_unlock(&debug_sync_global.ds_mutex);
1812   }
1813   else
1814   {
1815     /* purecov: begin tested */
1816     value= const_cast<char*>("OFF");
1817     /* purecov: end */
1818   }
1819 
1820   DBUG_RETURN((uchar*) value);
1821 }
1822 
1823 
1824 /**
1825   Return true if the signal is found in global signal list.
1826 
1827   @param signal Signal name identifying the signal.
1828 
1829   @note
1830     If signal is found in the global signal set, it means that the
1831     signal thread has signalled to the waiting thread. This method
1832     must be called with the debug_sync_global.ds_mutex held.
1833 
1834   @eretval true  if signal is found in the global signal list.
1835   @retval false otherwise.
1836 */
1837 
is_signalled(const std::string * signal_name)1838 static inline bool is_signalled(const std::string *signal_name)
1839 {
1840   return (debug_sync_global.ds_signal_set.find(*signal_name) !=
1841           debug_sync_global.ds_signal_set.end());
1842 }
1843 
1844 
1845 /**
1846   Return false if signal has been added to global signal list.
1847 
1848   @param signal signal name that is to be added to the global signal
1849          list.
1850 
1851   @note
1852     This method add signal name to the global signal list and signals
1853     the waiting thread that this signal has been emitted. This method
1854     must be called with the debug_sync_global.ds_mutex held.
1855 */
1856 
add_signal_event(const std::string * signal_name)1857 static inline void add_signal_event(const std::string *signal_name)
1858 {
1859   debug_sync_global.ds_signal_set.insert(*signal_name);
1860 }
1861 
1862 
1863 /**
1864   Remove the signal from the global signal list.
1865 
1866   @param signal signal name to be removed from the global signal list.
1867 
1868   @note
1869     This method erases the signal from the signal list.  This happens
1870     when the wait thread has processed the signal event from the
1871     signalling thread. This method should be called with the
1872     debug_sync_global.ds_mutex held.
1873 */
clear_signal_event(const std::string * signal_name)1874 static inline void clear_signal_event(const std::string *signal_name)
1875 {
1876   debug_sync_global.ds_signal_set.erase(*signal_name);
1877 }
1878 
1879 
1880 /**
1881   Execute requested action at a synchronization point.
1882 
1883   @param[in]    thd                 thread handle
1884   @param[in]    action              action to be executed
1885 
1886   @note
1887     This is to be called only if activation count > 0.
1888 */
1889 
debug_sync_execute(THD * thd,st_debug_sync_action * action)1890 static void debug_sync_execute(THD *thd, st_debug_sync_action *action)
1891 {
1892 #ifndef NDEBUG
1893   const char *dsp_name= action->sync_point.c_ptr();
1894   const char *sig_emit= action->signal.c_ptr();
1895   const char *sig_wait= action->wait_for.c_ptr();
1896 #endif
1897   DBUG_ENTER("debug_sync_execute");
1898   assert(thd);
1899   assert(action);
1900   DBUG_PRINT("debug_sync",
1901              ("sync_point: '%s'  activation_count: %lu  hit_limit: %lu  "
1902               "execute: %lu  timeout: %lu  signal: '%s'  wait_for: '%s'",
1903               dsp_name, action->activation_count, action->hit_limit,
1904               action->execute, action->timeout, sig_emit, sig_wait));
1905 
1906   assert(action->activation_count);
1907   action->activation_count--;
1908 
1909   if (action->execute)
1910   {
1911     const char *old_proc_info= NULL;
1912 
1913     action->execute--;
1914 
1915     /*
1916       If we will be going to wait, set proc_info for the PROCESSLIST table.
1917       Do this before emitting the signal, so other threads can see it
1918       if they awake before we enter_cond() below.
1919     */
1920     if (action->wait_for.length())
1921     {
1922       st_debug_sync_control *ds_control= thd->debug_sync_control;
1923       strxnmov(ds_control->ds_proc_info, sizeof(ds_control->ds_proc_info)-1,
1924                "debug sync point: ", action->sync_point.c_ptr(), NullS);
1925       old_proc_info= thd->proc_info;
1926       debug_sync_thd_proc_info(thd, ds_control->ds_proc_info);
1927     }
1928 
1929     /*
1930       Take mutex to ensure that only one thread access
1931       debug_sync_global.ds_signal_set at a time.  Need to take mutex for
1932       read access too, to create a memory barrier in order to avoid that
1933       threads just reads an old cached version of the signal.
1934     */
1935     mysql_mutex_lock(&debug_sync_global.ds_mutex);
1936 
1937     if (action->signal.length())
1938     {
1939       std::string signal= action->signal.ptr();
1940       std::vector<std::string> signals;
1941       boost::split(signals, signal, boost::is_any_of(","));
1942       for (std::vector<std::string>::const_iterator it= signals.begin();
1943 	   it != signals.end(); ++it)
1944       {
1945         /* Copy the signal to the global set. */
1946 	std::string s= *it;
1947 	boost::trim(s);
1948 	if (!s.empty())
1949           add_signal_event(&s);
1950       }
1951       /* Wake threads waiting in a sync point. */
1952       mysql_cond_broadcast(&debug_sync_global.ds_cond);
1953       DBUG_PRINT("debug_sync_exec", ("signal '%s'  at: '%s'",
1954                                      sig_emit, dsp_name));
1955     } /* end if (action->signal.length()) */
1956 
1957     if (action->wait_for.length())
1958     {
1959       mysql_mutex_t *old_mutex;
1960       mysql_cond_t  *old_cond= 0;
1961       int             error= 0;
1962       struct timespec abstime;
1963       std::string wait_for= action->wait_for.ptr();
1964 
1965       /*
1966         We don't use enter_cond()/exit_cond(). They do not save old
1967         mutex and cond. This would prohibit the use of DEBUG_SYNC
1968         between other places of enter_cond() and exit_cond().
1969 
1970         Note that we cannot lock LOCK_current_cond here. See comment
1971         in THD::enter_cond().
1972       */
1973       old_mutex= thd->current_mutex;
1974       old_cond= thd->current_cond;
1975       thd->current_mutex= &debug_sync_global.ds_mutex;
1976       thd->current_cond= &debug_sync_global.ds_cond;
1977 
1978       set_timespec(&abstime, action->timeout);
1979       DBUG_EXECUTE("debug_sync_exec", {
1980           DBUG_PRINT("debug_sync_exec",
1981                      ("wait for '%s'  at: '%s'",
1982                       sig_wait, dsp_name));});
1983       /*
1984         Wait until global signal string matches the wait_for string.
1985         Interrupt when thread or query is killed or facility disabled.
1986         The facility can become disabled when some thread cannot get
1987         the required dynamic memory allocated.
1988       */
1989       while (!is_signalled(&wait_for) &&
1990              !thd->killed && opt_debug_sync_timeout)
1991       {
1992         error= mysql_cond_timedwait(&debug_sync_global.ds_cond,
1993                                     &debug_sync_global.ds_mutex,
1994                                     &abstime);
1995 
1996         DBUG_EXECUTE("debug_sync", {
1997             /* Functions as DBUG_PRINT args can change keyword and line nr. */
1998             DBUG_PRINT("debug_sync",
1999                        ("awoke from %s error: %d", sig_wait, error)); });
2000 
2001         if (error == ETIMEDOUT || error == ETIME)
2002         {
2003           // We should not make the statement fail, even if in strict mode.
2004           push_warning(thd, Sql_condition::SL_WARNING,
2005                        ER_DEBUG_SYNC_TIMEOUT, ER(ER_DEBUG_SYNC_TIMEOUT));
2006           DBUG_EXECUTE_IF("debug_sync_abort_on_timeout", DBUG_ABORT(););
2007           break;
2008         }
2009         error= 0;
2010       }
2011       if (action->clear_event)
2012         clear_signal_event(&wait_for);
2013 
2014       DBUG_EXECUTE("debug_sync_exec",
2015                    if (thd->killed)
2016                      DBUG_PRINT("debug_sync_exec",
2017                                 ("killed %d from '%s'  at: '%s'",
2018                                  thd->killed, sig_wait, dsp_name));
2019                    else
2020                      DBUG_PRINT("debug_sync_exec",
2021                                 ("%s from '%s'  at: '%s'",
2022                                  error ? "timeout" : "resume",
2023                                  sig_wait, dsp_name)););
2024 
2025       /*
2026         We don't use enter_cond()/exit_cond(). They do not save old
2027         mutex and cond. This would prohibit the use of DEBUG_SYNC
2028         between other places of enter_cond() and exit_cond(). The
2029         protected mutex must always unlocked _before_ mysys_var->mutex
2030         is locked. (See comment in THD::exit_cond().)
2031       */
2032       mysql_mutex_unlock(&debug_sync_global.ds_mutex);
2033       if (old_mutex)
2034       {
2035         mysql_mutex_lock(&thd->LOCK_current_cond);
2036         thd->current_mutex= old_mutex;
2037         thd->current_cond= old_cond;
2038         mysql_mutex_unlock(&thd->LOCK_current_cond);
2039         debug_sync_thd_proc_info(thd, old_proc_info);
2040       }
2041       else
2042         debug_sync_thd_proc_info(thd, old_proc_info);
2043     }
2044     else
2045     {
2046       /* In case we don't wait, we just release the mutex. */
2047       mysql_mutex_unlock(&debug_sync_global.ds_mutex);
2048     } /* end if (action->wait_for.length()) */
2049 
2050   } /* end if (action->execute) */
2051 
2052   /* hit_limit is zero for infinite. Don't decrement unconditionally. */
2053   if (action->hit_limit)
2054   {
2055     if (!--action->hit_limit)
2056     {
2057       thd->killed= THD::KILL_QUERY;
2058       my_error(ER_DEBUG_SYNC_HIT_LIMIT, MYF(0));
2059     }
2060     DBUG_PRINT("debug_sync_exec", ("hit_limit: %lu  at: '%s'",
2061                                    action->hit_limit, dsp_name));
2062   }
2063 
2064   DBUG_VOID_RETURN;
2065 }
2066 
2067 
2068 /**
2069   Execute requested action at a synchronization point.
2070 
2071   @param[in]     thd                thread handle
2072   @param[in]     sync_point_name    name of synchronization point
2073   @param[in]     name_len           length of sync point name
2074 */
2075 
debug_sync(THD * thd,const char * sync_point_name,size_t name_len)2076 void debug_sync(THD *thd, const char *sync_point_name, size_t name_len)
2077 {
2078   if(!thd)
2079   {
2080     return;
2081   }
2082 
2083   st_debug_sync_control *ds_control= thd->debug_sync_control;
2084   st_debug_sync_action  *action;
2085   DBUG_ENTER("debug_sync");
2086   assert(thd);
2087   assert(sync_point_name);
2088   assert(name_len);
2089   assert(ds_control);
2090   DBUG_PRINT("debug_sync_point", ("hit: '%s'", sync_point_name));
2091 
2092   /* Statistics. */
2093   ds_control->dsp_hits++;
2094 
2095   if (ds_control->ds_active &&
2096       (action= debug_sync_find(ds_control->ds_action, ds_control->ds_active,
2097                                sync_point_name, name_len)) &&
2098       action->activation_count)
2099   {
2100     /* Sync point is active (action exists). */
2101     debug_sync_execute(thd, action);
2102 
2103     /* Statistics. */
2104     ds_control->dsp_executed++;
2105 
2106     /* If action became inactive, remove it to shrink the search array. */
2107     if (!action->activation_count)
2108       debug_sync_remove_action(ds_control, action);
2109   }
2110 
2111   DBUG_VOID_RETURN;
2112 }
2113 
2114 /**
2115   Define debug sync action.
2116 
2117   @param[in]        thd             thread handle
2118   @param[in]        action_str      action string
2119 
2120   @return           status
2121     @retval         FALSE           ok
2122     @retval         TRUE            error
2123 
2124   @description
2125     The function is similar to @c debug_sync_eval_action but is
2126     to be called immediately from the server code rather than
2127     to be triggered by setting a value to DEBUG_SYNC system variable.
2128 
2129   @note
2130     The input string is copied prior to be fed to
2131     @c debug_sync_eval_action to let the latter modify it.
2132 
2133     Caution.
2134     The function allocates in THD::mem_root and therefore
2135     is not recommended to be deployed inside big loops.
2136 */
2137 
debug_sync_set_action(THD * thd,const char * action_str,size_t len)2138 bool debug_sync_set_action(THD *thd, const char *action_str, size_t len)
2139 {
2140   bool                  rc;
2141   char *value;
2142   DBUG_ENTER("debug_sync_set_action");
2143   assert(thd);
2144   assert(action_str);
2145 
2146   value= strmake_root(thd->mem_root, action_str, len);
2147   rc= debug_sync_eval_action(thd, value);
2148   DBUG_RETURN(rc);
2149 }
2150 
2151 
2152 #endif /* defined(ENABLED_DEBUG_SYNC) */
2153