1 /*
2    Copyright (c) 2002, 2021, Oracle and/or its affiliates.
3 
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License, version 2.0,
6    as published by the Free Software Foundation.
7 
8    This program is also distributed with certain software (including
9    but not limited to OpenSSL) that is licensed under separate terms,
10    as designated in a particular file or component or in included license
11    documentation.  The authors of MySQL hereby grant you an additional
12    permission to link the program and your derivative works with the
13    separately licensed software that they have included with MySQL.
14 
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License, version 2.0, for more details.
19 
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA */
23 
24 #include "sp_head.h"
25 
26 #include "sql_cache.h"         // query_cache_*
27 #include "probes_mysql.h"
28 #include "sql_show.h"          // append_identifier
29 #include "sql_db.h"            // mysql_opt_change_db, mysql_change_db
30 #include "sql_table.h"         // prepare_create_field
31 #include "auth_common.h"       // *_ACL
32 #include "log_event.h"         // append_query_string, Query_log_event
33 #include "binlog.h"
34 
35 #include "sp_instr.h"
36 #include "sp.h"
37 #include "sp_pcontext.h"
38 #include "sp_rcontext.h"
39 #include "sp_cache.h"
40 #include "sql_parse.h"         // cleanup_items
41 #include "sql_base.h"          // close_thread_tables
42 #include "template_utils.h"    // pointer_cast
43 #include "transaction.h"       // trans_commit_stmt
44 #include "opt_trace.h"         // opt_trace_disable_etc
45 
46 #include <my_user.h>           // parse_user
47 #ifdef WITH_WSREP
48 #include "wsrep_thd.h"
49 #endif /* WITH_WSREP */
50 #include "mysql/psi/mysql_statement.h"
51 #include "mysql/psi/mysql_sp.h"
52 
53 #ifdef HAVE_PSI_INTERFACE
init_sp_psi_keys()54 void init_sp_psi_keys()
55 {
56   const char *category= "sp";
57 
58   PSI_server->register_statement(category, & sp_instr_stmt::psi_info, 1);
59   PSI_server->register_statement(category, & sp_instr_set::psi_info, 1);
60   PSI_server->register_statement(category, & sp_instr_set_trigger_field::psi_info, 1);
61   PSI_server->register_statement(category, & sp_instr_jump::psi_info, 1);
62   PSI_server->register_statement(category, & sp_instr_jump_if_not::psi_info, 1);
63   PSI_server->register_statement(category, & sp_instr_freturn::psi_info, 1);
64   PSI_server->register_statement(category, & sp_instr_hpush_jump::psi_info, 1);
65   PSI_server->register_statement(category, & sp_instr_hpop::psi_info, 1);
66   PSI_server->register_statement(category, & sp_instr_hreturn::psi_info, 1);
67   PSI_server->register_statement(category, & sp_instr_cpush::psi_info, 1);
68   PSI_server->register_statement(category, & sp_instr_cpop::psi_info, 1);
69   PSI_server->register_statement(category, & sp_instr_copen::psi_info, 1);
70   PSI_server->register_statement(category, & sp_instr_cclose::psi_info, 1);
71   PSI_server->register_statement(category, & sp_instr_cfetch::psi_info, 1);
72   PSI_server->register_statement(category, & sp_instr_error::psi_info, 1);
73   PSI_server->register_statement(category, & sp_instr_set_case_expr::psi_info, 1);
74 }
75 #endif
76 
77 /**
78   SP_TABLE represents all instances of one table in an optimized multi-set of
79   tables used by a stored program.
80 */
81 struct SP_TABLE
82 {
83   /*
84     Multi-set key:
85       db_name\0table_name\0alias\0 - for normal tables
86       db_name\0table_name\0        - for temporary tables
87     Note that in both cases we don't take last '\0' into account when
88     we count length of key.
89   */
90   LEX_STRING qname;
91   size_t db_length, table_name_length;
92   bool temp;               /* true if corresponds to a temporary table */
93   thr_lock_type lock_type; /* lock type used for prelocking */
94   uint lock_count;
95   uint query_lock_count;
96   uint8 trg_event_map;
97 };
98 
99 
100 ///////////////////////////////////////////////////////////////////////////
101 // Static function implementations.
102 ///////////////////////////////////////////////////////////////////////////
103 
104 
sp_table_key(const uchar * ptr,size_t * plen,my_bool first)105 uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first)
106 {
107   SP_TABLE *tab= (SP_TABLE *)ptr;
108   *plen= tab->qname.length;
109   return (uchar *)tab->qname.str;
110 }
111 
112 
113 /**
114   Helper function which operates on a THD object to set the query start_time to
115   the current time.
116 
117   @param thd  Thread context.
118 */
reset_start_time_for_sp(THD * thd)119 static void reset_start_time_for_sp(THD *thd)
120 {
121   if (thd->in_sub_stmt)
122     return;
123 
124   /*
125     First investigate if there is a cached time stamp
126   */
127   if (thd->user_time.tv_sec || thd->user_time.tv_usec)
128     thd->start_time= thd->user_time;
129   else
130     my_micro_time_to_timeval(my_micro_time(), &thd->start_time);
131 }
132 
133 
134 /**
135   Merge contents of two hashes representing sets of routines used
136   by statements or by other routines.
137 
138   @param dst   hash to which elements should be added
139   @param src   hash from which elements merged
140 
141   @note
142     This procedure won't create new Sroutine_hash_entry objects,
143     instead it will simply add elements from source to destination
144     hash. Thus time of life of elements in destination hash becomes
145     dependant on time of life of elements from source hash. It also
146     won't touch lists linking elements in source and destination
147     hashes.
148 
149     @return Error status.
150 */
151 
sp_update_sp_used_routines(HASH * dst,HASH * src)152 static bool sp_update_sp_used_routines(HASH *dst, HASH *src)
153 {
154   for (uint i= 0 ; i < src->records ; i++)
155   {
156     Sroutine_hash_entry *rt= (Sroutine_hash_entry *)my_hash_element(src, i);
157     if (!my_hash_search(dst, (uchar *)rt->mdl_request.key.ptr(),
158                         rt->mdl_request.key.length()))
159     {
160       if (my_hash_insert(dst, (uchar *)rt))
161         return true;
162     }
163   }
164   return false;
165 }
166 
167 ///////////////////////////////////////////////////////////////////////////
168 // sp_name implementation.
169 ///////////////////////////////////////////////////////////////////////////
170 
171 /**
172   Create temporary sp_name object from MDL key.
173 
174   @note The lifetime of this object is bound to the lifetime of the MDL_key.
175         This should be fine as sp_name objects created by this constructor
176         are mainly used for SP-cache lookups.
177 
178   @param key         MDL key containing database and routine name.
179   @param qname_buff  Buffer to be used for storing quoted routine name
180                      (should be at least 2*NAME_LEN+1+1 bytes).
181 */
182 
sp_name(const MDL_key * key,char * qname_buff)183 sp_name::sp_name(const MDL_key *key, char *qname_buff)
184 {
185   m_db.str= (char*)key->db_name();
186   m_db.length= key->db_name_length();
187   m_name.str= (char*)key->name();
188   m_name.length= key->name_length();
189   m_qname.str= qname_buff;
190   if (m_db.length)
191   {
192     strxmov(qname_buff, m_db.str, ".", m_name.str, NullS);
193     m_qname.length= m_db.length + 1 + m_name.length;
194   }
195   else
196   {
197     my_stpcpy(qname_buff, m_name.str);
198     m_qname.length= m_name.length;
199   }
200   m_explicit_name= false;
201 }
202 
203 
204 /**
205   Init the qualified name from the db and name.
206 */
init_qname(THD * thd)207 void sp_name::init_qname(THD *thd)
208 {
209   const uint dot= !!m_db.length;
210   /* m_qname format: [database + dot] + name + '\0' */
211   m_qname.length= m_db.length + dot + m_name.length;
212   if (!(m_qname.str= (char*) thd->alloc(m_qname.length + 1)))
213     return;
214   sprintf(m_qname.str, "%.*s%.*s%.*s",
215           (int) m_db.length, (m_db.length ? m_db.str : ""),
216           dot, ".",
217           (int) m_name.length, m_name.str);
218 }
219 
220 ///////////////////////////////////////////////////////////////////////////
221 // sp_head implementation.
222 ///////////////////////////////////////////////////////////////////////////
223 
operator new(size_t size)224 void *sp_head::operator new(size_t size) throw()
225 {
226   MEM_ROOT own_root;
227 
228   init_sql_alloc(key_memory_sp_head_main_root,
229                  &own_root, MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC);
230 
231   sp_head *sp= (sp_head *) alloc_root(&own_root, size);
232   if (!sp)
233     return NULL;
234 
235   sp->main_mem_root= own_root;
236   DBUG_PRINT("info", ("mem_root 0x%lx", (ulong) &sp->mem_root));
237   return sp;
238 }
239 
operator delete(void * ptr,size_t size)240 void sp_head::operator delete(void *ptr, size_t size) throw()
241 {
242   if (!ptr)
243     return;
244 
245   sp_head *sp= (sp_head *) ptr;
246 
247   /* Make a copy of main_mem_root as free_root will free the sp */
248   MEM_ROOT own_root= sp->main_mem_root;
249   DBUG_PRINT("info", ("mem_root 0x%lx moved to 0x%lx",
250                       (ulong) &sp->mem_root, (ulong) &own_root));
251   free_root(&own_root, MYF(0));
252 }
253 
254 
sp_head(enum_sp_type type)255 sp_head::sp_head(enum_sp_type type)
256  :Query_arena(&main_mem_root, STMT_INITIALIZED_FOR_SP),
257   m_type(type),
258   m_flags(0),
259   m_chistics(NULL),
260   m_sql_mode(0),
261   m_explicit_name(false),
262   m_created(0),
263   m_modified(0),
264   m_recursion_level(0),
265   m_next_cached_sp(NULL),
266   m_first_instance(NULL),
267   m_first_free_instance(NULL),
268   m_last_cached_sp(NULL),
269   m_trg_list(NULL),
270   m_root_parsing_ctx(NULL),
271   m_instructions(&main_mem_root),
272   m_sp_cache_version(0),
273   m_creation_ctx(NULL),
274   unsafe_flags(0)
275 {
276   m_first_instance= this;
277   m_first_free_instance= this;
278   m_last_cached_sp= this;
279 
280   m_instructions.reserve(32);
281 
282   m_return_field_def.charset = NULL;
283 
284   /*
285     FIXME: the only use case when name is NULL is events, and it should
286     be rewritten soon. Remove the else part and replace 'if' with
287     an assert when this is done.
288   */
289 
290   m_db= NULL_STR;
291   m_name= NULL_STR;
292   m_qname= NULL_STR;
293 
294   m_params= NULL_STR;
295 
296   m_defstr= NULL_STR;
297   m_body= NULL_STR;
298   m_body_utf8= NULL_STR;
299 
300   my_hash_init(&m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0,
301                key_memory_sp_head_main_root);
302   my_hash_init(&m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key,
303                0, 0,
304                key_memory_sp_head_main_root);
305 
306   m_trg_chistics.ordering_clause= TRG_ORDER_NONE;
307   m_trg_chistics.anchor_trigger_name.str= NULL;
308   m_trg_chistics.anchor_trigger_name.length= 0;
309 }
310 
311 
init_sp_name(THD * thd,sp_name * spname)312 void sp_head::init_sp_name(THD *thd, sp_name *spname)
313 {
314   /* Must be initialized in the parser. */
315 
316   assert(spname && spname->m_db.str && spname->m_db.length);
317 
318   /* We have to copy strings to get them into the right memroot. */
319 
320   m_db.length= spname->m_db.length;
321   m_db.str= strmake_root(thd->mem_root, spname->m_db.str, spname->m_db.length);
322 
323   m_name.length= spname->m_name.length;
324   m_name.str= strmake_root(thd->mem_root, spname->m_name.str,
325                            spname->m_name.length);
326 
327   m_explicit_name= spname->m_explicit_name;
328 
329   if (spname->m_qname.length == 0)
330     spname->init_qname(thd);
331 
332   m_qname.length= spname->m_qname.length;
333   m_qname.str= (char*) memdup_root(thd->mem_root,
334                                    spname->m_qname.str,
335                                    spname->m_qname.length + 1);
336 }
337 
338 
set_body_start(THD * thd,const char * begin_ptr)339 void sp_head::set_body_start(THD *thd, const char *begin_ptr)
340 {
341   m_parser_data.set_body_start_ptr(begin_ptr);
342 
343   thd->m_parser_state->m_lip.body_utf8_start(thd, begin_ptr);
344 }
345 
346 
set_body_end(THD * thd)347 void sp_head::set_body_end(THD *thd)
348 {
349   Lex_input_stream *lip= & thd->m_parser_state->m_lip; /* shortcut */
350   const char *end_ptr= lip->get_cpp_ptr(); /* shortcut */
351 
352   /* Make the string of parameters. */
353 
354   {
355     const char *p_start= m_parser_data.get_parameter_start_ptr();
356     const char *p_end= m_parser_data.get_parameter_end_ptr();
357 
358     if (p_start && p_end)
359     {
360       m_params.length= p_end - p_start;
361       m_params.str= thd->strmake(p_start, m_params.length);
362     }
363   }
364 
365   /* Remember end pointer for further dumping of whole statement. */
366 
367   thd->lex->stmt_definition_end= end_ptr;
368 
369   /* Make the string of body (in the original character set). */
370 
371   m_body.length= end_ptr - m_parser_data.get_body_start_ptr();
372   m_body.str= thd->strmake(m_parser_data.get_body_start_ptr(), m_body.length);
373   trim_whitespace(thd->charset(), & m_body);
374 
375   /* Make the string of UTF-body. */
376 
377   lip->body_utf8_append(end_ptr);
378 
379   m_body_utf8.length= lip->get_body_utf8_length();
380   m_body_utf8.str= thd->strmake(lip->get_body_utf8_str(), m_body_utf8.length);
381   trim_whitespace(thd->charset(), & m_body_utf8);
382 
383   /*
384     Make the string of whole stored-program-definition query (in the
385     original character set).
386   */
387 
388   m_defstr.length= end_ptr - lip->get_cpp_buf();
389   m_defstr.str= thd->strmake(lip->get_cpp_buf(), m_defstr.length);
390   trim_whitespace(thd->charset(), & m_defstr);
391 }
392 
393 
setup_trigger_fields(THD * thd,Table_trigger_field_support * tfs,GRANT_INFO * subject_table_grant,bool need_fix_fields)394 bool sp_head::setup_trigger_fields(THD *thd,
395                                    Table_trigger_field_support *tfs,
396                                    GRANT_INFO *subject_table_grant,
397                                    bool need_fix_fields)
398 {
399   for (SQL_I_List<Item_trigger_field> *trig_field_list=
400          m_list_of_trig_fields_item_lists.first;
401        trig_field_list;
402        trig_field_list= trig_field_list->first->next_trig_field_list)
403   {
404     for (Item_trigger_field *f= trig_field_list->first; f;
405          f= f->next_trg_field)
406     {
407       f->setup_field(thd, tfs, subject_table_grant);
408 
409       if (need_fix_fields &&
410           !f->fixed &&
411           f->fix_fields(thd, (Item **) NULL))
412       {
413         return true;
414       }
415     }
416   }
417 
418   return false;
419 }
420 
421 
mark_used_trigger_fields(TABLE * subject_table)422 void sp_head::mark_used_trigger_fields(TABLE *subject_table)
423 {
424   for (SQL_I_List<Item_trigger_field> *trig_field_list=
425          m_list_of_trig_fields_item_lists.first;
426        trig_field_list;
427        trig_field_list= trig_field_list->first->next_trig_field_list)
428   {
429     for (Item_trigger_field *f= trig_field_list->first; f;
430          f= f->next_trg_field)
431     {
432       if (f->field_idx == (uint) -1)
433       {
434         // We cannot mark fields which does not present in table.
435         continue;
436       }
437 
438       bitmap_set_bit(subject_table->read_set, f->field_idx);
439 
440       if (f->get_settable_routine_parameter())
441         bitmap_set_bit(subject_table->write_set, f->field_idx);
442     }
443   }
444 }
445 
446 
447 /**
448   Check whether any table's fields are used in trigger.
449 
450   @param [in] used_fields       bitmap of fields to check
451 
452   @return Check result
453     @retval true   Some table fields are used in trigger
454     @retval false  None of table fields are used in trigger
455 */
456 
has_updated_trigger_fields(const MY_BITMAP * used_fields) const457 bool sp_head::has_updated_trigger_fields(const MY_BITMAP *used_fields) const
458 {
459   for (SQL_I_List<Item_trigger_field> *trig_field_list=
460          m_list_of_trig_fields_item_lists.first;
461        trig_field_list;
462        trig_field_list= trig_field_list->first->next_trig_field_list)
463   {
464     for (Item_trigger_field *f= trig_field_list->first; f;
465          f= f->next_trg_field)
466     {
467       // We cannot check fields which does not present in table.
468       if (f->field_idx != (uint) -1)
469       {
470         if (bitmap_is_set(used_fields, f->field_idx) &&
471             f->get_settable_routine_parameter())
472           return true;
473       }
474     }
475   }
476 
477   return false;
478 }
479 
480 
~sp_head()481 sp_head::~sp_head()
482 {
483   LEX *lex;
484   sp_instr *i;
485 
486   // Parsing of SP-body must have been already finished.
487   assert(!m_parser_data.is_parsing_sp_body());
488 
489   for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
490     delete i;
491 
492   delete m_root_parsing_ctx;
493 
494   free_items();
495 
496   /*
497     If we have non-empty LEX stack then we just came out of parser with
498     error. Now we should delete all auxiliary LEXes and restore original
499     THD::lex. It is safe to not update LEX::ptr because further query
500     string parsing and execution will be stopped anyway.
501   */
502   while ((lex= m_parser_data.pop_lex()))
503   {
504     THD *thd= lex->thd;
505     thd->lex->sphead= NULL;
506     lex_end(thd->lex);
507     delete thd->lex;
508     thd->lex= lex;
509   }
510 
511   my_hash_free(&m_sptabs);
512   my_hash_free(&m_sroutines);
513 
514   delete m_next_cached_sp;
515 }
516 
517 
create_result_field(size_t field_max_length,const char * field_name,TABLE * table)518 Field *sp_head::create_result_field(size_t field_max_length,
519                                     const char *field_name,
520                                     TABLE *table)
521 {
522   size_t field_length= !m_return_field_def.length ?
523     field_max_length : m_return_field_def.length;
524 
525   Field *field=
526     ::make_field(table->s,                     /* TABLE_SHARE ptr */
527                  (uchar*) 0,                   /* field ptr */
528                  field_length,                 /* field [max] length */
529                  (uchar*) "",                  /* null ptr */
530                  0,                            /* null bit */
531                  m_return_field_def.pack_flag,
532                  m_return_field_def.sql_type,
533                  m_return_field_def.charset,
534                  m_return_field_def.geom_type,
535                  Field::NONE,                  /* unreg check */
536                  m_return_field_def.interval,
537                  field_name ? field_name : (const char *) m_name.str);
538 
539   field->gcol_info= m_return_field_def.gcol_info;
540   field->stored_in_db= m_return_field_def.stored_in_db;
541   if (field)
542     field->init(table);
543 
544   return field;
545 }
546 
547 
execute(THD * thd,bool merge_da_on_success)548 bool sp_head::execute(THD *thd, bool merge_da_on_success)
549 {
550   char saved_cur_db_name_buf[NAME_LEN+1];
551   LEX_STRING saved_cur_db_name=
552     { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
553   bool cur_db_changed= FALSE;
554   bool err_status= FALSE;
555   uint ip= 0;
556   sql_mode_t save_sql_mode;
557   Query_arena *old_arena;
558   /* per-instruction arena */
559   MEM_ROOT execute_mem_root;
560   Query_arena execute_arena(&execute_mem_root, STMT_INITIALIZED_FOR_SP),
561               backup_arena;
562   query_id_t old_query_id;
563   TABLE *old_derived_tables;
564   LEX *old_lex;
565   Item_change_list old_change_list;
566   String old_packet;
567   Object_creation_ctx *saved_creation_ctx;
568   Diagnostics_area *caller_da= thd->get_stmt_da();
569   Diagnostics_area sp_da(false);
570 
571   /*
572     Just reporting a stack overrun error
573     (@sa check_stack_overrun()) requires stack memory for error
574     message buffer. Thus, we have to put the below check
575     relatively close to the beginning of the execution stack,
576     where available stack margin is still big. As long as the check
577     has to be fairly high up the call stack, the amount of memory
578     we "book" for has to stay fairly high as well, and hence
579     not very accurate. The number below has been calculated
580     by trial and error, and reflects the amount of memory necessary
581     to execute a single stored procedure instruction, be it either
582     an SQL statement, or, heaviest of all, a CALL, which involves
583     parsing and loading of another stored procedure into the cache
584     (@sa db_load_routine() and Bug#10100).
585 
586     TODO: that should be replaced by proper handling of stack overrun error.
587 
588     Stack size depends on the platform:
589       - for most platforms (8 * STACK_MIN_SIZE) is enough;
590       - for Solaris SPARC 64 (10 * STACK_MIN_SIZE) is required.
591   */
592 
593   {
594 #if defined(__sparc) && defined(__SUNPRO_CC)
595     const int sp_stack_size= 10 * STACK_MIN_SIZE;
596 #else
597     const int sp_stack_size=  8 * STACK_MIN_SIZE;
598 #endif
599 
600     if (check_stack_overrun(thd, sp_stack_size, (uchar*) &old_packet))
601       return true;
602   }
603 
604   opt_trace_disable_if_no_security_context_access(thd);
605 
606   /* init per-instruction memroot */
607   init_sql_alloc(key_memory_sp_head_execute_root,
608                  &execute_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
609 
610   assert(!(m_flags & IS_INVOKED));
611   m_flags|= IS_INVOKED;
612   m_first_instance->m_first_free_instance= m_next_cached_sp;
613   if (m_next_cached_sp)
614   {
615     DBUG_PRINT("info",
616                ("first free for 0x%lx ++: 0x%lx->0x%lx  level: %lu  flags %x",
617                 (ulong)m_first_instance, (ulong) this,
618                 (ulong) m_next_cached_sp,
619                 m_next_cached_sp->m_recursion_level,
620                 m_next_cached_sp->m_flags));
621   }
622   /*
623     Check that if there are not any instances after this one then
624     pointer to the last instance points on this instance or if there are
625     some instances after this one then recursion level of next instance
626     greater then recursion level of current instance on 1
627   */
628   assert((m_next_cached_sp == 0 &&
629           m_first_instance->m_last_cached_sp == this) ||
630          (m_recursion_level + 1 == m_next_cached_sp->m_recursion_level));
631 
632   /*
633     NOTE: The SQL Standard does not specify the context that should be
634     preserved for stored routines. However, at SAP/Walldorf meeting it was
635     decided that current database should be preserved.
636   */
637   if (m_db.length &&
638       (err_status= mysql_opt_change_db(thd, to_lex_cstring(m_db),
639                                        &saved_cur_db_name, false,
640                                        &cur_db_changed)))
641   {
642     goto done;
643   }
644 
645   thd->is_slave_error= 0;
646   old_arena= thd->stmt_arena;
647 
648   /* Push a new Diagnostics Area. */
649   thd->push_diagnostics_area(&sp_da);
650 
651   /*
652     Switch query context. This has to be done early as this is sometimes
653     allocated trough sql_alloc
654   */
655   saved_creation_ctx= m_creation_ctx->set_n_backup(thd);
656 
657   /*
658     We have to save/restore this info when we are changing call level to
659     be able properly do close_thread_tables() in instructions.
660   */
661   old_query_id= thd->query_id;
662   old_derived_tables= thd->derived_tables;
663   thd->derived_tables= 0;
664   save_sql_mode= thd->variables.sql_mode;
665   thd->variables.sql_mode= m_sql_mode;
666   /**
667     When inside a substatement (a stored function or trigger
668     statement), clear the metadata observer in THD, if any.
669     Remember the value of the observer here, to be able
670     to restore it when leaving the substatement.
671 
672     We reset the observer to suppress errors when a substatement
673     uses temporary tables. If a temporary table does not exist
674     at start of the main statement, it's not prelocked
675     and thus is not validated with other prelocked tables.
676 
677     Later on, when the temporary table is opened, metadata
678     versions mismatch, expectedly.
679 
680     The proper solution for the problem is to re-validate tables
681     of substatements (Bug#12257, Bug#27011, Bug#32868, Bug#33000),
682     but it's not implemented yet.
683   */
684   thd->push_reprepare_observer(NULL);
685 
686   /*
687     It is also more efficient to save/restore current thd->lex once when
688     do it in each instruction
689   */
690   old_lex= thd->lex;
691   /*
692     We should also save Item tree change list to avoid rollback something
693     too early in the calling query.
694   */
695   thd->change_list.move_elements_to(&old_change_list);
696 
697   if (thd->is_classic_protocol())
698   {
699     /*
700       Cursors will use thd->packet, so they may corrupt data which was
701       prepared for sending by upper level. OTOH cursors in the same routine
702       can share this buffer safely so let use use routine-local packet
703       instead of having own packet buffer for each cursor.
704 
705       It is probably safe to use same thd->convert_buff everywhere.
706     */
707     old_packet.swap(*thd->get_protocol_classic()->get_packet());
708   }
709 
710   /*
711     Switch to per-instruction arena here. We can do it since we cleanup
712     arena after every instruction.
713   */
714   thd->set_n_backup_active_arena(&execute_arena, &backup_arena);
715 
716   /*
717     Save callers arena in order to store instruction results and out
718     parameters in it later during sp_eval_func_item()
719   */
720   thd->sp_runtime_ctx->callers_arena= &backup_arena;
721 
722 #if defined(ENABLED_PROFILING)
723   /* Discard the initial part of executing routines. */
724   thd->profiling.discard_current_query();
725 #endif
726   do
727   {
728     sp_instr *i;
729 
730 #if defined(ENABLED_PROFILING)
731     /*
732      Treat each "instr" of a routine as discrete unit that could be profiled.
733      Profiling only records information for segments of code that set the
734      source of the query, and almost all kinds of instructions in s-p do not.
735     */
736     thd->profiling.finish_current_query();
737     thd->profiling.start_new_query("continuing inside routine");
738 #endif
739 
740     /* get_instr returns NULL when we're done. */
741     i = get_instr(ip);
742     if (i == NULL)
743     {
744 #if defined(ENABLED_PROFILING)
745       thd->profiling.discard_current_query();
746 #endif
747       break;
748     }
749 
750     DBUG_PRINT("execute", ("Instruction %u", ip));
751 
752     /*
753       We need to reset start_time to allow for time to flow inside a stored
754       procedure. This is only done for SP since time is suppose to be constant
755       during execution of triggers and functions.
756     */
757     reset_start_time_for_sp(thd);
758 
759     /*
760       We have to set thd->stmt_arena before executing the instruction
761       to store in the instruction free_list all new items, created
762       during the first execution (for example expanding of '*' or the
763       items made during other permanent subquery transformations).
764     */
765     thd->stmt_arena= i;
766 
767     /*
768       Will write this SP statement into binlog separately.
769       TODO: consider changing the condition to "not inside event union".
770     */
771     if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
772       thd->user_var_events_alloc= thd->mem_root;
773 
774     sql_digest_state digest_state;
775     sql_digest_state *parent_digest= thd->m_digest;
776     thd->m_digest= & digest_state;
777 
778 #ifdef HAVE_PSI_STATEMENT_INTERFACE
779     PSI_statement_locker_state psi_state;
780     PSI_statement_info *psi_info = i->get_psi_info();
781     PSI_statement_locker *parent_locker;
782 
783     parent_locker= thd->m_statement_psi;
784     thd->m_statement_psi= MYSQL_START_STATEMENT(&psi_state, psi_info->m_key,
785                                                 thd->db().str,
786                                                 thd->db().length,
787                                                 thd->charset(),
788                                                 this->m_sp_share);
789 #endif
790 
791     /*
792       For now, we're mostly concerned with sp_instr_stmt, but that's
793       likely to change in the future, so we'll do it right from the
794       start.
795     */
796     if (thd->rewritten_query().length())
797       thd->reset_rewritten_query();
798 
799 #ifdef WITH_WSREP
800     if (thd->wsrep_next_trx_id() == WSREP_UNDEFINED_TRX_ID)
801     {
802       thd->set_wsrep_next_trx_id(thd->query_id);
803       WSREP_DEBUG("assigned new next trx ID for SP,  trx id: %lu", thd->wsrep_next_trx_id());
804     }
805 #endif /* WITH_WSREP */
806     err_status= i->execute(thd, &ip);
807 
808 #ifdef HAVE_PSI_STATEMENT_INTERFACE
809     MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da());
810     thd->m_statement_psi= parent_locker;
811 #endif
812 
813 #ifdef WITH_WSREP
814     if (m_type == SP_TYPE_PROCEDURE ||
815         m_type == SP_TYPE_EVENT)
816     {
817       mysql_mutex_lock(&thd->LOCK_wsrep_thd);
818       if (thd->wsrep_conflict_state == MUST_REPLAY)
819       {
820         wsrep_replay_sp_transaction(thd);
821         err_status= thd->get_stmt_da()->is_set();
822         thd->wsrep_conflict_state= NO_CONFLICT;
823       }
824       else if (thd->wsrep_conflict_state == ABORTED ||
825                thd->wsrep_conflict_state == CERT_FAILURE)
826       {
827         /*
828           If the statement execution was BF aborted or was aborted
829           due to certification failure, clean up transaction here
830           and reset conflict state to NO_CONFLICT and thd->killed
831           to THD::NOT_KILLED. Error handling is done based on err_status
832           below. Error must have been raised by wsrep hton code before
833           entering here.
834          */
835         assert(err_status);
836         assert(thd->get_stmt_da()->is_error());
837         thd->wsrep_conflict_state= NO_CONFLICT;
838         thd->killed= THD::NOT_KILLED;
839       }
840       mysql_mutex_unlock(&thd->LOCK_wsrep_thd);
841     }
842 #endif /* WITH_WSREP */
843     thd->m_digest= parent_digest;
844 
845     if (i->free_list)
846       cleanup_items(i->free_list);
847 
848     /*
849       If we've set thd->user_var_events_alloc to mem_root of this SP
850       statement, clean all the events allocated in it.
851     */
852     if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
853     {
854       thd->user_var_events.clear();
855       thd->user_var_events_alloc= NULL;//DEBUG
856     }
857 
858     /* we should cleanup free_list and memroot, used by instruction */
859     thd->cleanup_after_query();
860     free_root(&execute_mem_root, MYF(0));
861 
862     /*
863       Find and process SQL handlers unless it is a fatal error (fatal
864       errors are not catchable by SQL handlers) or the connection has been
865       killed during execution.
866     */
867     if (!thd->is_fatal_error && !thd->killed_errno() &&
868         thd->sp_runtime_ctx->handle_sql_condition(thd, &ip, i))
869     {
870       err_status= FALSE;
871     }
872 
873     /* Reset sp_rcontext::end_partial_result_set flag. */
874     thd->sp_runtime_ctx->end_partial_result_set= FALSE;
875 
876   } while (!err_status && !thd->killed && !thd->is_fatal_error);
877 
878 #if defined(ENABLED_PROFILING)
879   thd->profiling.finish_current_query();
880   thd->profiling.start_new_query("tail end of routine");
881 #endif
882 
883   /* Restore query context. */
884 
885   m_creation_ctx->restore_env(thd, saved_creation_ctx);
886 
887   /* Restore arena. */
888 
889   thd->restore_active_arena(&execute_arena, &backup_arena);
890 
891   thd->sp_runtime_ctx->pop_all_cursors(); // To avoid memory leaks after an error
892 
893   if(thd->is_classic_protocol())
894     /* Restore all saved */
895     old_packet.swap(*thd->get_protocol_classic()->get_packet());
896   assert(thd->change_list.is_empty());
897   old_change_list.move_elements_to(&thd->change_list);
898   thd->lex= old_lex;
899   thd->set_query_id(old_query_id);
900   assert(!thd->derived_tables);
901   thd->derived_tables= old_derived_tables;
902   thd->variables.sql_mode= save_sql_mode;
903   thd->pop_reprepare_observer();
904 
905   thd->stmt_arena= old_arena;
906   state= STMT_EXECUTED;
907 
908   if (err_status && thd->is_error() && !caller_da->is_error())
909   {
910     /*
911       If the SP ended with an exception, transfer the exception condition
912       information to the Diagnostics Area of the caller.
913 
914       Note that no error might be set yet in the case of kill.
915       It will be set later by mysql_execute_command() / execute_trigger().
916 
917       In the case of multi update, it is possible that we can end up
918       executing a trigger after the update has failed. In this case,
919       keep the exception condition from the caller_da and don't transfer.
920     */
921     caller_da->set_error_status(thd->get_stmt_da()->mysql_errno(),
922                                 thd->get_stmt_da()->message_text(),
923                                 thd->get_stmt_da()->returned_sqlstate());
924   }
925 
926   /*
927     - conditions generated during trigger execution should not be
928     propagated to the caller on success;   (merge_da_on_success)
929     - if there was an exception during execution, conditions should be
930     propagated to the caller in any case.  (err_status)
931   */
932   if (err_status || merge_da_on_success)
933   {
934     /*
935       If a routine body is empty or if a routine did not generate any
936       conditions, do not duplicate our own contents by appending the contents
937       of the called routine. We know that the called routine did not change its
938       Diagnostics Area.
939 
940       On the other hand, if the routine body is not empty and some statement
941       in the routine generates a condition, Diagnostics Area is guaranteed to
942       have changed. In this case we know that the routine Diagnostics Area
943       contains only new conditions, and thus we perform a copy.
944 
945       We don't use push_warning() here as to avoid invocation of
946       condition handlers or escalation of warnings to errors.
947     */
948     if (!err_status && thd->get_stmt_da() != &sp_da)
949     {
950       /*
951         If we are RETURNing directly from a handler and the handler has
952         executed successfully, only transfer the conditions that were
953         raised during handler execution. Conditions that were present
954         when the handler was activated, are considered handled.
955       */
956       caller_da->copy_new_sql_conditions(thd, thd->get_stmt_da());
957     }
958     else // err_status || thd->get_stmt_da() == sp_da
959     {
960       /*
961         If we ended with an exception, or the SP exited without any handler
962         active, transfer all conditions to the Diagnostics Area of the caller.
963       */
964       caller_da->copy_sql_conditions_from_da(thd, thd->get_stmt_da());
965     }
966   }
967 
968   // Restore the caller's original Diagnostics Area.
969   while (thd->get_stmt_da() != &sp_da)
970     thd->pop_diagnostics_area();
971   thd->pop_diagnostics_area();
972   assert(thd->get_stmt_da() == caller_da);
973 
974  done:
975   DBUG_PRINT("info", ("err_status: %d  killed: %d  is_slave_error: %d  report_error: %d",
976                       err_status, thd->killed, thd->is_slave_error,
977                       thd->is_error()));
978 
979   if (thd->killed)
980     err_status= TRUE;
981   /*
982     If the DB has changed, the pointer has changed too, but the
983     original thd->db will then have been freed
984   */
985   if (cur_db_changed && thd->killed != THD::KILL_CONNECTION)
986   {
987     /*
988       Force switching back to the saved current database, because it may be
989       NULL. In this case, mysql_change_db() would generate an error.
990     */
991 
992     err_status|= mysql_change_db(thd, to_lex_cstring(saved_cur_db_name), true);
993   }
994   m_flags&= ~IS_INVOKED;
995   DBUG_PRINT("info",
996              ("first free for 0x%lx --: 0x%lx->0x%lx, level: %lu, flags %x",
997               (ulong) m_first_instance,
998               (ulong) m_first_instance->m_first_free_instance,
999               (ulong) this, m_recursion_level, m_flags));
1000   /*
1001     Check that we have one of following:
1002 
1003     1) there are not free instances which means that this instance is last
1004     in the list of instances (pointer to the last instance point on it and
1005     there are not other instances after this one in the list)
1006 
1007     2) There are some free instances which mean that first free instance
1008     should go just after this one and recursion level of that free instance
1009     should be on 1 more then recursion level of this instance.
1010   */
1011   assert((m_first_instance->m_first_free_instance == 0 &&
1012           this == m_first_instance->m_last_cached_sp &&
1013           m_next_cached_sp == 0) ||
1014          (m_first_instance->m_first_free_instance != 0 &&
1015           m_first_instance->m_first_free_instance == m_next_cached_sp &&
1016           m_first_instance->m_first_free_instance->m_recursion_level ==
1017           m_recursion_level + 1));
1018   m_first_instance->m_first_free_instance= this;
1019 
1020   return err_status;
1021 }
1022 
1023 
execute_trigger(THD * thd,const LEX_CSTRING & db_name,const LEX_CSTRING & table_name,GRANT_INFO * grant_info)1024 bool sp_head::execute_trigger(THD *thd,
1025                               const LEX_CSTRING &db_name,
1026                               const LEX_CSTRING &table_name,
1027                               GRANT_INFO *grant_info)
1028 {
1029   sp_rcontext *parent_sp_runtime_ctx = thd->sp_runtime_ctx;
1030   bool err_status= FALSE;
1031   MEM_ROOT call_mem_root;
1032   Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
1033   Query_arena backup_arena;
1034 
1035   DBUG_ENTER("sp_head::execute_trigger");
1036   DBUG_PRINT("info", ("trigger %s", m_name.str));
1037 
1038 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1039   Security_context *save_ctx= NULL;
1040   LEX_CSTRING definer_user= {m_definer_user.str, m_definer_user.length};
1041   LEX_CSTRING definer_host= {m_definer_host.str, m_definer_host.length};
1042 
1043   if (m_chistics->suid != SP_IS_NOT_SUID &&
1044       m_security_ctx.change_security_context(thd,
1045                                              definer_user,
1046                                              definer_host,
1047                                              &m_db,
1048                                              &save_ctx))
1049     DBUG_RETURN(true);
1050 
1051   /*
1052     Fetch information about table-level privileges for subject table into
1053     GRANT_INFO instance. The access check itself will happen in
1054     Item_trigger_field, where this information will be used along with
1055     information about column-level privileges.
1056   */
1057 
1058   fill_effective_table_privileges(thd,
1059                                   grant_info,
1060                                   db_name.str,
1061                                   table_name.str);
1062 
1063   /* Check that the definer has TRIGGER privilege on the subject table. */
1064 
1065   if (!(grant_info->privilege & TRIGGER_ACL))
1066   {
1067     char priv_desc[128];
1068     get_privilege_desc(priv_desc, sizeof(priv_desc), TRIGGER_ACL);
1069 
1070     my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), priv_desc,
1071              thd->security_context()->priv_user().str,
1072              thd->security_context()->host_or_ip().str,
1073              table_name.str);
1074 
1075     m_security_ctx.restore_security_context(thd, save_ctx);
1076     DBUG_RETURN(true);
1077   }
1078   /*
1079     Optimizer trace note: we needn't explicitly test here that the connected
1080     user has TRIGGER privilege: assume he doesn't have it; two possibilities:
1081     - connected user == definer: then we threw an error just above;
1082     - connected user != definer: then in sp_head::execute(), when checking the
1083     security context we will disable tracing.
1084   */
1085 #endif // NO_EMBEDDED_ACCESS_CHECKS
1086 
1087   /*
1088     Prepare arena and memroot for objects which lifetime is whole
1089     duration of trigger call (sp_rcontext, it's tables and items,
1090     sp_cursor and Item_cache holders for case expressions).  We can't
1091     use caller's arena/memroot for those objects because in this case
1092     some fixed amount of memory will be consumed for each trigger
1093     invocation and so statements which involve lot of them will hog
1094     memory.
1095 
1096     TODO: we should create sp_rcontext once per command and reuse it
1097     on subsequent executions of a trigger.
1098   */
1099   init_sql_alloc(key_memory_sp_head_call_root,
1100                  &call_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
1101   thd->set_n_backup_active_arena(&call_arena, &backup_arena);
1102 
1103   sp_rcontext *trigger_runtime_ctx=
1104     sp_rcontext::create(thd, m_root_parsing_ctx, NULL);
1105 
1106   if (!trigger_runtime_ctx)
1107   {
1108     err_status= TRUE;
1109     goto err_with_cleanup;
1110   }
1111 
1112   trigger_runtime_ctx->sp= this;
1113   thd->sp_runtime_ctx= trigger_runtime_ctx;
1114 
1115 #ifdef HAVE_PSI_SP_INTERFACE
1116   PSI_sp_locker_state psi_state;
1117   PSI_sp_locker *locker;
1118 
1119   locker= MYSQL_START_SP(&psi_state, m_sp_share);
1120 #endif
1121   err_status= execute(thd, FALSE);
1122 #ifdef HAVE_PSI_SP_INTERFACE
1123   MYSQL_END_SP(locker);
1124 #endif
1125 
1126 err_with_cleanup:
1127   thd->restore_active_arena(&call_arena, &backup_arena);
1128 
1129 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1130   m_security_ctx.restore_security_context(thd, save_ctx);
1131 #endif // NO_EMBEDDED_ACCESS_CHECKS
1132 
1133   delete trigger_runtime_ctx;
1134   call_arena.free_items();
1135   free_root(&call_mem_root, MYF(0));
1136   thd->sp_runtime_ctx= parent_sp_runtime_ctx;
1137 
1138   if (thd->killed)
1139     thd->send_kill_message();
1140 
1141   DBUG_RETURN(err_status);
1142 }
1143 
1144 
execute_function(THD * thd,Item ** argp,uint argcount,Field * return_value_fld)1145 bool sp_head::execute_function(THD *thd, Item **argp, uint argcount,
1146                                Field *return_value_fld)
1147 {
1148   ulonglong binlog_save_options= 0;
1149   bool need_binlog_call= FALSE;
1150   uint arg_no;
1151   sp_rcontext *parent_sp_runtime_ctx = thd->sp_runtime_ctx;
1152   char buf[STRING_BUFFER_USUAL_SIZE];
1153   String binlog_buf(buf, sizeof(buf), &my_charset_bin);
1154   bool err_status= FALSE;
1155   MEM_ROOT call_mem_root;
1156   Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
1157   Query_arena backup_arena;
1158 
1159   DBUG_ENTER("sp_head::execute_function");
1160   DBUG_PRINT("info", ("function %s", m_name.str));
1161 
1162   // Resetting THD::where to its default value
1163   thd->where= THD::DEFAULT_WHERE;
1164   /*
1165     Check that the function is called with all specified arguments.
1166 
1167     If it is not, use my_error() to report an error, or it will not terminate
1168     the invoking query properly.
1169   */
1170   if (argcount != m_root_parsing_ctx->context_var_count())
1171   {
1172     /*
1173       Need to use my_error here, or it will not terminate the
1174       invoking query properly.
1175     */
1176     my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0),
1177              "FUNCTION", m_qname.str,
1178              m_root_parsing_ctx->context_var_count(), argcount);
1179     DBUG_RETURN(true);
1180   }
1181   /*
1182     Prepare arena and memroot for objects which lifetime is whole
1183     duration of function call (sp_rcontext, it's tables and items,
1184     sp_cursor and Item_cache holders for case expressions).
1185     We can't use caller's arena/memroot for those objects because
1186     in this case some fixed amount of memory will be consumed for
1187     each function/trigger invocation and so statements which involve
1188     lot of them will hog memory.
1189     TODO: we should create sp_rcontext once per command and reuse
1190     it on subsequent executions of a function/trigger.
1191   */
1192   init_sql_alloc(key_memory_sp_head_call_root,
1193                  &call_mem_root, MEM_ROOT_BLOCK_SIZE, 0);
1194   thd->set_n_backup_active_arena(&call_arena, &backup_arena);
1195 
1196   sp_rcontext *func_runtime_ctx= sp_rcontext::create(thd, m_root_parsing_ctx,
1197                                                      return_value_fld);
1198 
1199   if (!func_runtime_ctx)
1200   {
1201     thd->restore_active_arena(&call_arena, &backup_arena);
1202     err_status= TRUE;
1203     goto err_with_cleanup;
1204   }
1205 
1206   func_runtime_ctx->sp= this;
1207 
1208   /*
1209     We have to switch temporarily back to callers arena/memroot.
1210     Function arguments belong to the caller and so the may reference
1211     memory which they will allocate during calculation long after
1212     this function call will be finished (e.g. in Item::cleanup()).
1213   */
1214   thd->restore_active_arena(&call_arena, &backup_arena);
1215 
1216   /*
1217     Pass arguments.
1218 
1219     Note, THD::sp_runtime_ctx must not be switched before the arguments are
1220     passed. Values are taken from the caller's runtime context and set to the
1221     runtime context of this function.
1222   */
1223   for (arg_no= 0; arg_no < argcount; arg_no++)
1224   {
1225     /* Arguments must be fixed in Item_func_sp::fix_fields */
1226     assert(argp[arg_no]->fixed);
1227 
1228     err_status= func_runtime_ctx->set_variable(thd, arg_no, &(argp[arg_no]));
1229 
1230     if (err_status)
1231       goto err_with_cleanup;
1232   }
1233 
1234   /*
1235     If row-based binlogging, we don't need to binlog the function's call, let
1236     each substatement be binlogged its way.
1237   */
1238   need_binlog_call= mysql_bin_log.is_open() &&
1239                     (thd->variables.option_bits & OPTION_BIN_LOG) &&
1240                     !thd->is_current_stmt_binlog_format_row();
1241 
1242   /*
1243     Remember the original arguments for unrolled replication of functions
1244     before they are changed by execution.
1245 
1246     Note, THD::sp_runtime_ctx must not be switched before the arguments are
1247     logged. Values are taken from the caller's runtime context.
1248   */
1249   if (need_binlog_call)
1250   {
1251     binlog_buf.length(0);
1252     binlog_buf.append(STRING_WITH_LEN("SELECT "));
1253     append_identifier(thd, &binlog_buf, m_db.str, m_db.length);
1254     binlog_buf.append('.');
1255     append_identifier(thd, &binlog_buf, m_name.str, m_name.length);
1256     binlog_buf.append('(');
1257     for (arg_no= 0; arg_no < argcount; arg_no++)
1258     {
1259       String str_value_holder;
1260       String *str_value;
1261 
1262       if (arg_no)
1263         binlog_buf.append(',');
1264 
1265       str_value= sp_get_item_value(thd, func_runtime_ctx->get_item(arg_no),
1266                                    &str_value_holder);
1267 
1268       if (str_value)
1269         binlog_buf.append(*str_value);
1270       else
1271         binlog_buf.append(STRING_WITH_LEN("NULL"));
1272     }
1273     binlog_buf.append(')');
1274   }
1275 
1276   thd->sp_runtime_ctx= func_runtime_ctx;
1277 
1278 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1279   Security_context *save_security_ctx;
1280   if (set_security_ctx(thd, &save_security_ctx))
1281   {
1282     err_status= TRUE;
1283     goto err_with_cleanup;
1284   }
1285 #endif
1286 
1287   if (need_binlog_call)
1288   {
1289     query_id_t q;
1290     thd->user_var_events.clear();
1291     /*
1292       In case of artificially constructed events for function calls
1293       we have separate union for each such event and hence can't use
1294       query_id of real calling statement as the start of all these
1295       unions (this will break logic of replication of user-defined
1296       variables). So we use artificial value which is guaranteed to
1297       be greater than all query_id's of all statements belonging
1298       to previous events/unions.
1299       Possible alternative to this is logging of all function invocations
1300       as one select and not resetting THD::user_var_events before
1301       each invocation.
1302     */
1303     q= my_atomic_load64(&global_query_id);
1304     mysql_bin_log.start_union_events(thd, q + 1);
1305     binlog_save_options= thd->variables.option_bits;
1306     thd->variables.option_bits&= ~OPTION_BIN_LOG;
1307   }
1308 
1309   opt_trace_disable_if_no_stored_proc_func_access(thd, this);
1310 
1311   /*
1312     Switch to call arena/mem_root so objects like sp_cursor or
1313     Item_cache holders for case expressions can be allocated on it.
1314 
1315     TODO: In future we should associate call arena/mem_root with
1316           sp_rcontext and allocate all these objects (and sp_rcontext
1317           itself) on it directly rather than juggle with arenas.
1318   */
1319   thd->set_n_backup_active_arena(&call_arena, &backup_arena);
1320 
1321 #ifdef HAVE_PSI_SP_INTERFACE
1322   PSI_sp_locker_state psi_state;
1323   PSI_sp_locker *locker;
1324 
1325   locker= MYSQL_START_SP(&psi_state, m_sp_share);
1326 #endif
1327   err_status= execute(thd, TRUE);
1328 #ifdef HAVE_PSI_SP_INTERFACE
1329   MYSQL_END_SP(locker);
1330 #endif
1331 
1332   thd->restore_active_arena(&call_arena, &backup_arena);
1333 
1334   if (need_binlog_call)
1335   {
1336     mysql_bin_log.stop_union_events(thd);
1337     thd->variables.option_bits= binlog_save_options;
1338     if (thd->binlog_evt_union.unioned_events)
1339     {
1340       int errcode = query_error_code(thd, thd->killed == THD::NOT_KILLED);
1341       Query_log_event qinfo(thd, binlog_buf.ptr(), binlog_buf.length(),
1342                             thd->binlog_evt_union.unioned_events_trans, FALSE, FALSE, errcode);
1343       if (mysql_bin_log.write_event(&qinfo) &&
1344           thd->binlog_evt_union.unioned_events_trans)
1345       {
1346         push_warning(thd, Sql_condition::SL_WARNING, ER_UNKNOWN_ERROR,
1347                      "Invoked ROUTINE modified a transactional table but MySQL "
1348                      "failed to reflect this change in the binary log");
1349         err_status= TRUE;
1350       }
1351       thd->user_var_events.clear();
1352       /* Forget those values, in case more function calls are binlogged: */
1353       thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
1354       thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
1355     }
1356   }
1357 
1358   if (!err_status)
1359   {
1360     /* We need result only in function but not in trigger */
1361 
1362     if (!thd->sp_runtime_ctx->is_return_value_set())
1363     {
1364       my_error(ER_SP_NORETURNEND, MYF(0), m_name.str);
1365       err_status= TRUE;
1366     }
1367   }
1368 
1369 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1370   m_security_ctx.restore_security_context(thd, save_security_ctx);
1371 #endif
1372 
1373 err_with_cleanup:
1374   delete func_runtime_ctx;
1375   call_arena.free_items();
1376   free_root(&call_mem_root, MYF(0));
1377   thd->sp_runtime_ctx= parent_sp_runtime_ctx;
1378 
1379   /*
1380     If not inside a procedure and a function printing warning
1381     messages.
1382   */
1383   if (need_binlog_call &&
1384       thd->sp_runtime_ctx == NULL && !thd->binlog_evt_union.do_union)
1385     thd->issue_unsafe_warnings();
1386 
1387   DBUG_RETURN(err_status);
1388 }
1389 
1390 
execute_procedure(THD * thd,List<Item> * args)1391 bool sp_head::execute_procedure(THD *thd, List<Item> *args)
1392 {
1393   bool err_status= FALSE;
1394   uint params = m_root_parsing_ctx->context_var_count();
1395   /* Query start time may be reset in a multi-stmt SP; keep this for later. */
1396   ulonglong utime_before_sp_exec= thd->utime_after_lock;
1397   sp_rcontext *parent_sp_runtime_ctx= thd->sp_runtime_ctx;
1398   sp_rcontext *sp_runtime_ctx_saved= thd->sp_runtime_ctx;
1399   bool save_enable_slow_log= false;
1400   bool save_log_general= false;
1401 
1402   DBUG_ENTER("sp_head::execute_procedure");
1403   DBUG_PRINT("info", ("procedure %s", m_name.str));
1404 
1405   if (args->elements != params)
1406   {
1407     my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "PROCEDURE",
1408              m_qname.str, params, args->elements);
1409     DBUG_RETURN(true);
1410   }
1411 
1412   if (!parent_sp_runtime_ctx)
1413   {
1414     // Create a temporary old context. We need it to pass OUT-parameter values.
1415     parent_sp_runtime_ctx= sp_rcontext::create(thd, m_root_parsing_ctx, NULL);
1416 
1417     if (!parent_sp_runtime_ctx)
1418       DBUG_RETURN(true);
1419 
1420     parent_sp_runtime_ctx->sp= 0;
1421     thd->sp_runtime_ctx= parent_sp_runtime_ctx;
1422 
1423     /* set callers_arena to thd, for upper-level function to work */
1424     thd->sp_runtime_ctx->callers_arena= thd;
1425   }
1426 
1427   sp_rcontext *proc_runtime_ctx=
1428     sp_rcontext::create(thd, m_root_parsing_ctx, NULL);
1429 
1430   if (!proc_runtime_ctx)
1431   {
1432     thd->sp_runtime_ctx= sp_runtime_ctx_saved;
1433 
1434     if (!sp_runtime_ctx_saved)
1435       delete parent_sp_runtime_ctx;
1436 
1437     DBUG_RETURN(true);
1438   }
1439 
1440   proc_runtime_ctx->sp= this;
1441 
1442   if (params > 0)
1443   {
1444     List_iterator<Item> it_args(*args);
1445 
1446     DBUG_PRINT("info",(" %.*s: eval args", (int) m_name.length, m_name.str));
1447 
1448     for (uint i= 0 ; i < params ; i++)
1449     {
1450       Item *arg_item= it_args++;
1451 
1452       if (!arg_item)
1453         break;
1454 
1455       sp_variable *spvar= m_root_parsing_ctx->find_variable(i);
1456 
1457       if (!spvar)
1458         continue;
1459 
1460       if (spvar->mode != sp_variable::MODE_IN)
1461       {
1462         Settable_routine_parameter *srp=
1463           arg_item->get_settable_routine_parameter();
1464 
1465         if (!srp)
1466         {
1467           my_error(ER_SP_NOT_VAR_ARG, MYF(0), i+1, m_qname.str);
1468           err_status= TRUE;
1469           break;
1470         }
1471 
1472         srp->set_required_privilege(spvar->mode == sp_variable::MODE_INOUT);
1473       }
1474 
1475       if (spvar->mode == sp_variable::MODE_OUT)
1476       {
1477         Item_null *null_item= new Item_null();
1478 
1479         if (!null_item ||
1480             proc_runtime_ctx->set_variable(thd, i, (Item **)&null_item))
1481         {
1482           err_status= TRUE;
1483           break;
1484         }
1485       }
1486       else
1487       {
1488         if (proc_runtime_ctx->set_variable(thd, i, it_args.ref()))
1489         {
1490           err_status= TRUE;
1491           break;
1492         }
1493       }
1494 
1495       if (thd->variables.session_track_transaction_info > TX_TRACK_NONE)
1496       {
1497         ((Transaction_state_tracker *)
1498          thd->session_tracker.get_tracker(TRANSACTION_INFO_TRACKER))
1499           ->add_trx_state_from_thd(thd);
1500       }
1501     }
1502 
1503     /*
1504       Okay, got values for all arguments. Close tables that might be used by
1505       arguments evaluation. If arguments evaluation required prelocking mode,
1506       we'll leave it here.
1507     */
1508     thd->lex->unit->cleanup(true);
1509 
1510     if (!thd->in_sub_stmt)
1511     {
1512       thd->get_stmt_da()->set_overwrite_status(true);
1513       thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
1514       thd->get_stmt_da()->set_overwrite_status(false);
1515     }
1516 
1517     thd_proc_info(thd, "closing tables");
1518     close_thread_tables(thd);
1519     thd_proc_info(thd, 0);
1520 
1521     if (! thd->in_sub_stmt)
1522     {
1523       if (thd->transaction_rollback_request)
1524       {
1525         trans_rollback_implicit(thd);
1526         thd->mdl_context.release_transactional_locks();
1527       }
1528       else if (! thd->in_multi_stmt_transaction_mode())
1529         thd->mdl_context.release_transactional_locks();
1530       else
1531         thd->mdl_context.release_statement_locks();
1532     }
1533 
1534     thd->rollback_item_tree_changes();
1535 
1536     DBUG_PRINT("info",(" %.*s: eval args done", (int) m_name.length,
1537                        m_name.str));
1538   }
1539   if (!(m_flags & LOG_SLOW_STATEMENTS) && thd->enable_slow_log)
1540   {
1541     DBUG_PRINT("info", ("Disabling slow log for the execution"));
1542     save_enable_slow_log= true;
1543     thd->enable_slow_log= FALSE;
1544   }
1545   if (!(m_flags & LOG_GENERAL_LOG) && !(thd->variables.option_bits & OPTION_LOG_OFF))
1546   {
1547     DBUG_PRINT("info", ("Disabling general log for the execution"));
1548     save_log_general= true;
1549     /* disable this bit */
1550     thd->variables.option_bits |= OPTION_LOG_OFF;
1551   }
1552   thd->sp_runtime_ctx= proc_runtime_ctx;
1553 
1554 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1555   Security_context *save_security_ctx= 0;
1556   if (!err_status)
1557     err_status= set_security_ctx(thd, &save_security_ctx);
1558 #endif
1559 
1560   opt_trace_disable_if_no_stored_proc_func_access(thd, this);
1561 
1562 #ifdef HAVE_PSI_SP_INTERFACE
1563   PSI_sp_locker_state psi_state;
1564   PSI_sp_locker *locker;
1565 
1566   locker= MYSQL_START_SP(&psi_state, m_sp_share);
1567 #endif
1568   if (!err_status)
1569     err_status= execute(thd, TRUE);
1570 #ifdef HAVE_PSI_SP_INTERFACE
1571   MYSQL_END_SP(locker);
1572 #endif
1573 
1574   if (save_log_general)
1575     thd->variables.option_bits &= ~OPTION_LOG_OFF;
1576   if (save_enable_slow_log)
1577     thd->enable_slow_log= true;
1578   /*
1579     In the case when we weren't able to employ reuse mechanism for
1580     OUT/INOUT parameters, we should reallocate memory. This
1581     allocation should be done on the arena which will live through
1582     all execution of calling routine.
1583   */
1584   thd->sp_runtime_ctx->callers_arena= parent_sp_runtime_ctx->callers_arena;
1585 
1586   if (!err_status && params > 0)
1587   {
1588     List_iterator<Item> it_args(*args);
1589 
1590     /*
1591       Copy back all OUT or INOUT values to the previous frame, or
1592       set global user variables
1593     */
1594     for (uint i= 0 ; i < params ; i++)
1595     {
1596       Item *arg_item= it_args++;
1597 
1598       if (!arg_item)
1599         break;
1600 
1601       sp_variable *spvar= m_root_parsing_ctx->find_variable(i);
1602 
1603       if (spvar->mode == sp_variable::MODE_IN)
1604         continue;
1605 
1606       Settable_routine_parameter *srp=
1607         arg_item->get_settable_routine_parameter();
1608 
1609       assert(srp);
1610 
1611       if (srp->set_value(thd, parent_sp_runtime_ctx, proc_runtime_ctx->get_item_addr(i)))
1612       {
1613         err_status= TRUE;
1614         break;
1615       }
1616 
1617       Send_field *out_param_info= new (thd->mem_root) Send_field();
1618       proc_runtime_ctx->get_item(i)->make_field(out_param_info);
1619       out_param_info->db_name= m_db.str;
1620       out_param_info->table_name= m_name.str;
1621       out_param_info->org_table_name= m_name.str;
1622       out_param_info->col_name= spvar->name.str;
1623       out_param_info->org_col_name= spvar->name.str;
1624 
1625       srp->set_out_param_info(out_param_info);
1626     }
1627   }
1628 
1629 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1630   if (save_security_ctx)
1631     m_security_ctx.restore_security_context(thd, save_security_ctx);
1632 #endif
1633 
1634   if (!sp_runtime_ctx_saved)
1635     delete parent_sp_runtime_ctx;
1636 
1637   delete proc_runtime_ctx;
1638   thd->sp_runtime_ctx= sp_runtime_ctx_saved;
1639   thd->utime_after_lock= utime_before_sp_exec;
1640 
1641   /*
1642     If not insided a procedure and a function printing warning
1643     messages.
1644   */
1645   bool need_binlog_call= mysql_bin_log.is_open() &&
1646                          (thd->variables.option_bits & OPTION_BIN_LOG) &&
1647                          !thd->is_current_stmt_binlog_format_row();
1648   if (need_binlog_call && thd->sp_runtime_ctx == NULL &&
1649       !thd->binlog_evt_union.do_union)
1650     thd->issue_unsafe_warnings();
1651 
1652   DBUG_RETURN(err_status);
1653 }
1654 
1655 
reset_lex(THD * thd)1656 bool sp_head::reset_lex(THD *thd)
1657 {
1658   LEX *oldlex= thd->lex;
1659 
1660   LEX *sublex= new (thd->mem_root)st_lex_local;
1661 
1662   if (!sublex)
1663     return true;
1664 
1665   thd->lex= sublex;
1666   m_parser_data.push_lex(oldlex);
1667 
1668   /* Reset most stuff. */
1669   lex_start(thd);
1670 
1671   /* And keep the SP stuff too */
1672   sublex->sphead= oldlex->sphead;
1673   sublex->set_sp_current_parsing_ctx(oldlex->get_sp_current_parsing_ctx());
1674   sublex->sp_lex_in_use= FALSE;
1675 
1676   /* Reset type info. */
1677 
1678   sublex->charset= NULL;
1679   sublex->length= NULL;
1680   sublex->dec= NULL;
1681   sublex->interval_list.empty();
1682   sublex->type= 0;
1683 
1684   /* Reset part of parser state which needs this. */
1685   thd->m_parser_state->m_yacc.reset_before_substatement();
1686 
1687   return false;
1688 }
1689 
1690 
restore_lex(THD * thd)1691 bool sp_head::restore_lex(THD *thd)
1692 {
1693   LEX *sublex= thd->lex;
1694 
1695   sublex->set_trg_event_type_for_tables();
1696 
1697   LEX *oldlex= m_parser_data.pop_lex();
1698 
1699   if (!oldlex)
1700     return false; // Nothing to restore
1701 
1702   /* If this substatement is unsafe, the entire routine is too. */
1703   DBUG_PRINT("info", ("lex->get_stmt_unsafe_flags: 0x%x",
1704                       thd->lex->get_stmt_unsafe_flags()));
1705   unsafe_flags|= sublex->get_stmt_unsafe_flags();
1706 
1707   /*
1708     Add routines which are used by statement to respective set for
1709     this routine.
1710   */
1711   if (sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines))
1712     return true;
1713 
1714   /* If this substatement is a update query, then mark MODIFIES_DATA */
1715   if (is_update_query(sublex->sql_command))
1716     m_flags|= MODIFIES_DATA;
1717 
1718   /*
1719     Merge tables used by this statement (but not by its functions or
1720     procedures) to multiset of tables used by this routine.
1721   */
1722   merge_table_list(thd, sublex->query_tables, sublex);
1723 
1724   if (!sublex->sp_lex_in_use)
1725   {
1726     sublex->sphead= NULL;
1727     lex_end(sublex);
1728     delete sublex;
1729   }
1730 
1731   thd->lex= oldlex;
1732   return false;
1733 }
1734 
set_info(longlong created,longlong modified,st_sp_chistics * chistics,sql_mode_t sql_mode)1735 void sp_head::set_info(longlong created,
1736                        longlong modified,
1737                        st_sp_chistics *chistics,
1738                        sql_mode_t sql_mode)
1739 {
1740   m_created= created;
1741   m_modified= modified;
1742   m_chistics= (st_sp_chistics *) memdup_root(mem_root, (char*) chistics,
1743                                              sizeof(*chistics));
1744   if (m_chistics->comment.length == 0)
1745     m_chistics->comment.str= 0;
1746   else
1747     m_chistics->comment.str= strmake_root(mem_root,
1748                                           m_chistics->comment.str,
1749                                           m_chistics->comment.length);
1750   m_sql_mode= sql_mode;
1751 }
1752 
1753 
set_definer(const char * definer,size_t definerlen)1754 void sp_head::set_definer(const char *definer, size_t definerlen)
1755 {
1756   char user_name_holder[USERNAME_LENGTH + 1];
1757   LEX_CSTRING user_name= { user_name_holder, USERNAME_LENGTH };
1758 
1759   char host_name_holder[HOSTNAME_LENGTH + 1];
1760   LEX_CSTRING host_name= { host_name_holder, HOSTNAME_LENGTH };
1761 
1762   parse_user(definer, definerlen,
1763              user_name_holder, &user_name.length,
1764              host_name_holder, &host_name.length);
1765 
1766   set_definer(user_name, host_name);
1767 }
1768 
1769 
set_definer(const LEX_CSTRING & user_name,const LEX_CSTRING & host_name)1770 void sp_head::set_definer(const LEX_CSTRING &user_name,
1771                           const LEX_CSTRING &host_name)
1772 {
1773   m_definer_user.str= strmake_root(mem_root, user_name.str, user_name.length);
1774   m_definer_user.length= user_name.length;
1775 
1776   m_definer_host.str= strmake_root(mem_root, host_name.str, host_name.length);
1777   m_definer_host.length= host_name.length;
1778 }
1779 
1780 
show_create_routine(THD * thd,enum_sp_type type)1781 bool sp_head::show_create_routine(THD *thd, enum_sp_type type)
1782 {
1783   const char *col1_caption= (type == SP_TYPE_PROCEDURE) ?
1784                             "Procedure" : "Function";
1785 
1786   const char *col3_caption= (type == SP_TYPE_PROCEDURE) ?
1787                             "Create Procedure" : "Create Function";
1788 
1789   bool err_status;
1790 
1791   Protocol *protocol= thd->get_protocol();
1792   List<Item> fields;
1793 
1794   LEX_STRING sql_mode;
1795 
1796   bool full_access;
1797 
1798   assert(type == SP_TYPE_PROCEDURE || type == SP_TYPE_FUNCTION);
1799 
1800   if (check_show_access(thd, &full_access))
1801     return true;
1802 
1803   sql_mode_string_representation(thd, m_sql_mode, &sql_mode);
1804 
1805   /* Send header. */
1806 
1807   fields.push_back(new Item_empty_string(col1_caption, NAME_CHAR_LEN));
1808   fields.push_back(new Item_empty_string("sql_mode", sql_mode.length));
1809 
1810   {
1811     /*
1812       NOTE: SQL statement field must be not less than 1024 in order not to
1813       confuse old clients.
1814     */
1815 
1816     Item_empty_string *stmt_fld=
1817       new Item_empty_string(col3_caption,
1818                             std::max<size_t>(m_defstr.length, 1024U));
1819 
1820     stmt_fld->maybe_null= TRUE;
1821 
1822     fields.push_back(stmt_fld);
1823   }
1824 
1825   fields.push_back(new Item_empty_string("character_set_client",
1826                                          MY_CS_NAME_SIZE));
1827 
1828   fields.push_back(new Item_empty_string("collation_connection",
1829                                          MY_CS_NAME_SIZE));
1830 
1831   fields.push_back(new Item_empty_string("Database Collation",
1832                                          MY_CS_NAME_SIZE));
1833 
1834   if (thd->send_result_metadata(&fields,
1835                                 Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
1836   {
1837     return true;
1838   }
1839 
1840   /* Send data. */
1841 
1842   protocol->start_row();
1843 
1844   protocol->store(m_name.str, m_name.length, system_charset_info);
1845   protocol->store(sql_mode.str, sql_mode.length, system_charset_info);
1846 
1847   if (full_access)
1848     protocol->store(m_defstr.str, m_defstr.length,
1849                     m_creation_ctx->get_client_cs());
1850   else
1851     protocol->store_null();
1852 
1853 
1854   protocol->store(m_creation_ctx->get_client_cs()->csname, system_charset_info);
1855   protocol->store(m_creation_ctx->get_connection_cl()->name, system_charset_info);
1856   protocol->store(m_creation_ctx->get_db_cl()->name, system_charset_info);
1857 
1858   err_status= protocol->end_row();
1859 
1860   if (!err_status)
1861     my_eof(thd);
1862 
1863   return err_status;
1864 }
1865 
1866 
add_instr(THD * thd,sp_instr * instr)1867 bool sp_head::add_instr(THD *thd, sp_instr *instr)
1868 {
1869   m_parser_data.process_new_sp_instr(thd, instr);
1870 
1871   if (m_type == SP_TYPE_TRIGGER && m_cur_instr_trig_field_items.elements)
1872   {
1873     SQL_I_List<Item_trigger_field> *instr_trig_fld_list;
1874     /*
1875       Move all the Item_trigger_field from "sp_head::
1876       m_cur_instr_trig_field_items" to the per instruction Item_trigger_field
1877       list "sp_lex_instr::m_trig_field_list" and clear "sp_head::
1878       m_cur_instr_trig_field_items".
1879     */
1880     if ((instr_trig_fld_list= instr->get_instr_trig_field_list()) != NULL)
1881     {
1882       m_cur_instr_trig_field_items.save_and_clear(instr_trig_fld_list);
1883       m_list_of_trig_fields_item_lists.link_in_list(instr_trig_fld_list,
1884         &instr_trig_fld_list->first->next_trig_field_list);
1885     }
1886   }
1887 
1888   /*
1889     Memory root of every instruction is designated for permanent
1890     transformations (optimizations) made on the parsed tree during
1891     the first execution. It points to the memory root of the
1892     entire stored procedure, as their life span is equal.
1893   */
1894   instr->mem_root= get_persistent_mem_root();
1895 
1896   return m_instructions.push_back(instr);
1897 }
1898 
1899 
optimize()1900 void sp_head::optimize()
1901 {
1902   List<sp_branch_instr> bp;
1903   sp_instr *i;
1904   uint src, dst;
1905 
1906   opt_mark();
1907 
1908   bp.empty();
1909   src= dst= 0;
1910   while ((i= get_instr(src)))
1911   {
1912     if (!i->opt_is_marked())
1913     {
1914       delete i;
1915       src+= 1;
1916     }
1917     else
1918     {
1919       if (src != dst)
1920       {
1921         m_instructions[dst]= i;
1922 
1923         /* Move the instruction and update prev. jumps */
1924         sp_branch_instr *ibp;
1925         List_iterator_fast<sp_branch_instr> li(bp);
1926 
1927         while ((ibp= li++))
1928           ibp->set_destination(src, dst);
1929       }
1930       i->opt_move(dst, &bp);
1931       src+= 1;
1932       dst+= 1;
1933     }
1934   }
1935 
1936   m_instructions.resize(dst);
1937   bp.empty();
1938 }
1939 
1940 
add_mark_lead(uint ip,List<sp_instr> * leads)1941 void sp_head::add_mark_lead(uint ip, List<sp_instr> *leads)
1942 {
1943   sp_instr *i= get_instr(ip);
1944 
1945   if (i && !i->opt_is_marked())
1946     leads->push_front(i);
1947 }
1948 
1949 
opt_mark()1950 void sp_head::opt_mark()
1951 {
1952   uint ip;
1953   sp_instr *i;
1954   List<sp_instr> leads;
1955 
1956   /*
1957     Forward flow analysis algorithm in the instruction graph:
1958     - first, add the entry point in the graph (the first instruction) to the
1959       'leads' list of paths to explore.
1960     - while there are still leads to explore:
1961       - pick one lead, and follow the path forward. Mark instruction reached.
1962         Stop only if the end of the routine is reached, or the path converge
1963         to code already explored (marked).
1964       - while following a path, collect in the 'leads' list any fork to
1965         another path (caused by conditional jumps instructions), so that these
1966         paths can be explored as well.
1967   */
1968 
1969   /* Add the entry point */
1970   i= get_instr(0);
1971   leads.push_front(i);
1972 
1973   /* For each path of code ... */
1974   while (leads.elements != 0)
1975   {
1976     i= leads.pop();
1977 
1978     /* Mark the entire path, collecting new leads. */
1979     while (i && !i->opt_is_marked())
1980     {
1981       ip= i->opt_mark(this, & leads);
1982       i= get_instr(ip);
1983     }
1984   }
1985 }
1986 
1987 
1988 #ifndef NDEBUG
show_routine_code(THD * thd)1989 bool sp_head::show_routine_code(THD *thd)
1990 {
1991   Protocol *protocol= thd->get_protocol();
1992   char buff[2048];
1993   String buffer(buff, sizeof(buff), system_charset_info);
1994   List<Item> field_list;
1995   sp_instr *i;
1996   bool full_access;
1997   bool res= false;
1998   uint ip;
1999 
2000   if (check_show_access(thd, &full_access) || !full_access)
2001     return true;
2002 
2003   field_list.push_back(new Item_uint(NAME_STRING("Pos"), 0, 9));
2004   // 1024 is for not to confuse old clients
2005   field_list.push_back(new Item_empty_string("Instruction",
2006                                              std::max<size_t>(buffer.length(), 1024U)));
2007   if (thd->send_result_metadata(&field_list,
2008                                 Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
2009     return true;
2010 
2011   for (ip= 0; (i = get_instr(ip)) ; ip++)
2012   {
2013     /*
2014       Consistency check. If these are different something went wrong
2015       during optimization.
2016     */
2017     if (ip != i->get_ip())
2018     {
2019       const char *format= "Instruction at position %u has m_ip=%u";
2020       char tmp[64 + 2 * MY_INT32_NUM_DECIMAL_DIGITS];
2021       sprintf(tmp, format, ip, i->get_ip());
2022       /*
2023         Since this is for debugging purposes only, we don't bother to
2024         introduce a special error code for it.
2025       */
2026       push_warning(thd, Sql_condition::SL_WARNING, ER_UNKNOWN_ERROR, tmp);
2027     }
2028     protocol->start_row();
2029     protocol->store((longlong)ip);
2030 
2031     buffer.set("", 0, system_charset_info);
2032     i->print(&buffer);
2033     protocol->store(buffer.ptr(), buffer.length(), system_charset_info);
2034     if ((res= protocol->end_row()))
2035       break;
2036   }
2037 
2038   if (!res)
2039     my_eof(thd);
2040 
2041   return res;
2042 }
2043 #endif // ifndef NDEBUG
2044 
2045 
merge_table_list(THD * thd,TABLE_LIST * table,LEX * lex_for_tmp_check)2046 bool sp_head::merge_table_list(THD *thd,
2047                                TABLE_LIST *table,
2048                                LEX *lex_for_tmp_check)
2049 {
2050   if (lex_for_tmp_check->sql_command == SQLCOM_DROP_TABLE &&
2051       lex_for_tmp_check->drop_temporary)
2052     return true;
2053 
2054   for (uint i= 0 ; i < m_sptabs.records ; i++)
2055   {
2056     SP_TABLE *tab= (SP_TABLE*) my_hash_element(&m_sptabs, i);
2057     tab->query_lock_count= 0;
2058   }
2059 
2060   for (; table ; table= table->next_global)
2061     if (!table->is_derived() && !table->schema_table)
2062     {
2063       /*
2064         Structure of key for the multi-set is "db\0table\0alias\0".
2065         Since "alias" part can have arbitrary length we use String
2066         object to construct the key. By default String will use
2067         buffer allocated on stack with NAME_LEN bytes reserved for
2068         alias, since in most cases it is going to be smaller than
2069         NAME_LEN bytes.
2070       */
2071       char tname_buff[(NAME_LEN + 1) * 3];
2072       String tname(tname_buff, sizeof(tname_buff), &my_charset_bin);
2073       size_t temp_table_key_length;
2074 
2075       tname.length(0);
2076       tname.append(table->db, table->db_length);
2077       tname.append('\0');
2078       tname.append(table->table_name, table->table_name_length);
2079       tname.append('\0');
2080       temp_table_key_length= tname.length();
2081       tname.append(table->alias);
2082       tname.append('\0');
2083 
2084       /*
2085         We ignore alias when we check if table was already marked as temporary
2086         (and therefore should not be prelocked). Otherwise we will erroneously
2087         treat table with same name but with different alias as non-temporary.
2088       */
2089 
2090       SP_TABLE *tab;
2091 
2092       if ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(),
2093                                            tname.length())) ||
2094           ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(),
2095                                             temp_table_key_length)) &&
2096            tab->temp))
2097       {
2098         if (tab->lock_type < table->lock_type)
2099           tab->lock_type= table->lock_type; // Use the table with the highest lock type
2100         tab->query_lock_count++;
2101         if (tab->query_lock_count > tab->lock_count)
2102           tab->lock_count++;
2103         tab->trg_event_map|= table->trg_event_map;
2104       }
2105       else
2106       {
2107         if (!(tab= (SP_TABLE *)thd->mem_calloc(sizeof(SP_TABLE))))
2108           return false;
2109         if (lex_for_tmp_check->sql_command == SQLCOM_CREATE_TABLE &&
2110             lex_for_tmp_check->query_tables == table &&
2111             lex_for_tmp_check->create_info.options & HA_LEX_CREATE_TMP_TABLE)
2112         {
2113           tab->temp= true;
2114           tab->qname.length= temp_table_key_length;
2115         }
2116         else
2117           tab->qname.length= tname.length();
2118         tab->qname.str= (char*) thd->memdup(tname.ptr(), tab->qname.length);
2119         if (!tab->qname.str)
2120           return false;
2121         tab->table_name_length= table->table_name_length;
2122         tab->db_length= table->db_length;
2123         tab->lock_type= table->lock_type;
2124         tab->lock_count= tab->query_lock_count= 1;
2125         tab->trg_event_map= table->trg_event_map;
2126         if (my_hash_insert(&m_sptabs, (uchar *)tab))
2127           return false;
2128       }
2129     }
2130   return true;
2131 }
2132 
2133 
add_used_tables_to_table_list(THD * thd,TABLE_LIST *** query_tables_last_ptr,enum_sql_command sql_command,TABLE_LIST * belong_to_view)2134 void sp_head::add_used_tables_to_table_list(THD *thd,
2135                                             TABLE_LIST ***query_tables_last_ptr,
2136                                             enum_sql_command sql_command,
2137                                             TABLE_LIST *belong_to_view)
2138 {
2139   /*
2140     Use persistent arena for table list allocation to be PS/SP friendly.
2141     Note that we also have to copy database/table names and alias to PS/SP
2142     memory since current instance of sp_head object can pass away before
2143     next execution of PS/SP for which tables are added to prelocking list.
2144     This will be fixed by introducing of proper invalidation mechanism
2145     once new TDC is ready.
2146   */
2147   Prepared_stmt_arena_holder ps_arena_holder(thd);
2148 
2149   for (uint i= 0; i < m_sptabs.records; i++)
2150   {
2151     SP_TABLE *stab= pointer_cast<SP_TABLE*>(my_hash_element(&m_sptabs, i));
2152     if (stab->temp)
2153       continue;
2154 
2155     char *tab_buff= static_cast<char*>
2156       (thd->alloc(ALIGN_SIZE(sizeof(TABLE_LIST)) * stab->lock_count));
2157     char *key_buff= static_cast<char*>(thd->memdup(stab->qname.str,
2158                                                    stab->qname.length));
2159     if (!tab_buff || !key_buff)
2160       return;
2161 
2162     for (uint j= 0; j < stab->lock_count; j++)
2163     {
2164       /*
2165         Since we don't allow DDL on base tables in prelocked mode it
2166         is safe to infer the type of metadata lock from the type of
2167         table lock.
2168       */
2169       enum_mdl_type mdl_lock_type;
2170 
2171       if (sql_command == SQLCOM_LOCK_TABLES)
2172       {
2173         /*
2174           We are building a table list for LOCK TABLES. We need to
2175           acquire "strong" locks to ensure that LOCK TABLES properly
2176           works for storage engines which don't use THR_LOCK locks.
2177         */
2178         mdl_lock_type= (stab->lock_type >= TL_WRITE_ALLOW_WRITE) ?
2179                        MDL_SHARED_NO_READ_WRITE : MDL_SHARED_READ_ONLY;
2180       }
2181       else
2182       {
2183         /*
2184           For other statements "normal" locks can be acquired.
2185           Let us respect explicit LOW_PRIORITY clause if was used
2186           in the routine.
2187         */
2188         mdl_lock_type= mdl_type_for_dml(stab->lock_type);
2189       }
2190 
2191       TABLE_LIST *table= pointer_cast<TABLE_LIST*>(tab_buff);
2192       table->init_one_table(key_buff, stab->db_length,
2193                             key_buff + stab->db_length + 1,
2194                             stab->table_name_length,
2195                             key_buff + stab->db_length + 1 +
2196                             stab->table_name_length + 1,
2197                             stab->lock_type, mdl_lock_type);
2198 
2199       table->cacheable_table= 1;
2200       table->prelocking_placeholder= 1;
2201       table->belong_to_view= belong_to_view;
2202       table->trg_event_map= stab->trg_event_map;
2203 
2204       /* Everyting else should be zeroed */
2205 
2206       **query_tables_last_ptr= table;
2207       table->prev_global= *query_tables_last_ptr;
2208       *query_tables_last_ptr= &table->next_global;
2209 
2210       tab_buff+= ALIGN_SIZE(sizeof(TABLE_LIST));
2211     }
2212   }
2213 }
2214 
2215 
check_show_access(THD * thd,bool * full_access)2216 bool sp_head::check_show_access(THD *thd, bool *full_access)
2217 {
2218   TABLE_LIST tables;
2219 
2220   tables.db= (char*) "mysql";
2221   tables.table_name= tables.alias= (char*) "proc";
2222 
2223   *full_access=
2224     ((!check_table_access(thd, SELECT_ACL, &tables, false, 1, true) &&
2225       (tables.grant.privilege & SELECT_ACL) != 0) ||
2226      (!strcmp(m_definer_user.str, thd->security_context()->priv_user().str) &&
2227       !strcmp(m_definer_host.str, thd->security_context()->priv_host().str)));
2228 
2229   return *full_access ?
2230          false :
2231          check_some_routine_access(thd, m_db.str, m_name.str,
2232                                    m_type == SP_TYPE_PROCEDURE);
2233 }
2234 
2235 
2236 #ifndef NO_EMBEDDED_ACCESS_CHECKS
set_security_ctx(THD * thd,Security_context ** save_ctx)2237 bool sp_head::set_security_ctx(THD *thd, Security_context **save_ctx)
2238 {
2239   *save_ctx= NULL;
2240   LEX_CSTRING definer_user= {m_definer_user.str, m_definer_user.length};
2241   LEX_CSTRING definer_host= {m_definer_host.str, m_definer_host.length};
2242 
2243   if (m_chistics->suid != SP_IS_NOT_SUID &&
2244       m_security_ctx.change_security_context(thd,
2245                                              definer_user, definer_host,
2246                                              &m_db, save_ctx))
2247   {
2248     return true;
2249   }
2250 
2251   /*
2252     If we changed context to run as another user, we need to check the
2253     access right for the new context again as someone may have revoked
2254     the right to use the procedure from this user.
2255   */
2256 
2257   if (*save_ctx &&
2258       check_routine_access(thd, EXECUTE_ACL, m_db.str, m_name.str,
2259                            m_type == SP_TYPE_PROCEDURE, false))
2260   {
2261     m_security_ctx.restore_security_context(thd, *save_ctx);
2262     *save_ctx= NULL;
2263     return true;
2264   }
2265 
2266   return false;
2267 }
2268 #endif // ! NO_EMBEDDED_ACCESS_CHECKS
2269 
2270 
2271 ///////////////////////////////////////////////////////////////////////////
2272 // sp_parser_data implementation.
2273 ///////////////////////////////////////////////////////////////////////////
2274 
2275 
start_parsing_sp_body(THD * thd,sp_head * sp)2276 void sp_parser_data::start_parsing_sp_body(THD *thd, sp_head *sp)
2277 {
2278   m_saved_memroot= thd->mem_root;
2279   m_saved_free_list= thd->free_list;
2280 
2281   thd->mem_root= sp->get_persistent_mem_root();
2282   set_memroot_max_capacity(thd->mem_root, m_saved_memroot->max_capacity);
2283   set_memroot_error_reporting(thd->mem_root, m_saved_memroot->error_for_capacity_exceeded);
2284   thd->free_list= NULL;
2285 }
2286 
2287 
add_backpatch_entry(sp_branch_instr * i,sp_label * label)2288 bool sp_parser_data::add_backpatch_entry(sp_branch_instr *i,
2289                                          sp_label *label)
2290 {
2291   Backpatch_info *bp= (Backpatch_info *)sql_alloc(sizeof(Backpatch_info));
2292 
2293   if (!bp)
2294     return true;
2295 
2296   bp->label= label;
2297   bp->instr= i;
2298   return m_backpatch.push_front(bp);
2299 }
2300 
2301 
do_backpatch(sp_label * label,uint dest)2302 void sp_parser_data::do_backpatch(sp_label *label, uint dest)
2303 {
2304   Backpatch_info *bp;
2305   List_iterator_fast<Backpatch_info> li(m_backpatch);
2306 
2307   while ((bp= li++))
2308   {
2309     if (bp->label == label)
2310       bp->instr->backpatch(dest);
2311   }
2312 }
2313 
2314 
add_cont_backpatch_entry(sp_lex_branch_instr * i)2315 bool sp_parser_data::add_cont_backpatch_entry(sp_lex_branch_instr *i)
2316 {
2317   i->set_cont_dest(m_cont_level);
2318   return m_cont_backpatch.push_front(i);
2319 }
2320 
2321 
do_cont_backpatch(uint dest)2322 void sp_parser_data::do_cont_backpatch(uint dest)
2323 {
2324   sp_lex_branch_instr *i;
2325 
2326   while ((i= m_cont_backpatch.head()) && i->get_cont_dest() == m_cont_level)
2327   {
2328     i->set_cont_dest(dest);
2329     m_cont_backpatch.pop();
2330   }
2331 
2332   --m_cont_level;
2333 }
2334 
2335 
process_new_sp_instr(THD * thd,sp_instr * i)2336 void sp_parser_data::process_new_sp_instr(THD* thd, sp_instr *i)
2337 {
2338   /*
2339     thd->free_list should be cleaned here because it's implicitly expected
2340     that that process_new_sp_instr() (called from sp_head::add_instr) is
2341     called as the last action after parsing the SP-instruction's SQL query.
2342 
2343     Thus, at this point thd->free_list contains all Item-objects, created for
2344     this SP-instruction.
2345 
2346     Next SP-instruction should start its own free-list from the scratch.
2347   */
2348 
2349   i->free_list= thd->free_list;
2350 
2351   thd->free_list= NULL;
2352 }
2353