1 /*
2    Copyright (c) 2002, 2016, Oracle and/or its affiliates.
3    Copyright (c) 2011, 2017, MariaDB
4 
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; version 2 of the License.
8 
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13 
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */
17 
18 #include "mariadb.h"                          /* NO_EMBEDDED_ACCESS_CHECKS */
19 #include "sql_priv.h"
20 #include "unireg.h"
21 #include "sql_prepare.h"
22 #include "sql_cache.h"                          // query_cache_*
23 #include "probes_mysql.h"
24 #include "sql_show.h"                           // append_identifier
25 #include "sql_db.h"            // mysql_opt_change_db, mysql_change_db
26 #include "sql_acl.h"           // *_ACL
27 #include "sql_array.h"         // Dynamic_array
28 #include "log_event.h"         // Query_log_event
29 #include "sql_derived.h"       // mysql_handle_derived
30 #include "sql_cte.h"
31 #include "sql_select.h"        // Virtual_tmp_table
32 
33 #ifdef USE_PRAGMA_IMPLEMENTATION
34 #pragma implementation
35 #endif
36 #include "sp_head.h"
37 #include "sp.h"
38 #include "sp_pcontext.h"
39 #include "sp_rcontext.h"
40 #include "sp_cache.h"
41 #include "set_var.h"
42 #include "sql_parse.h"                          // cleanup_items
43 #include "sql_base.h"                           // close_thread_tables
44 #include "transaction.h"       // trans_commit_stmt
45 #include "sql_audit.h"
46 #include "debug_sync.h"
47 #ifdef WITH_WSREP
48 #include "wsrep_thd.h"
49 #endif /* WITH_WSREP */
50 
51 /*
52   Sufficient max length of printed destinations and frame offsets (all uints).
53 */
54 #define SP_INSTR_UINT_MAXLEN  8
55 #define SP_STMT_PRINT_MAXLEN 40
56 
57 
58 #include <my_user.h>
59 
60 extern "C" uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first);
61 
project<'pin>( self: ::pin_project::__private::Pin<&'pin mut Self>, ) -> __StructProjection<'pin, T, U>62 /**
63   Helper function which operates on a THD object to set the query start_time to
64   the current time.
65 
66   @param[in, out] thd The session object
67 
68 */
69 
70 static void reset_start_time_for_sp(THD *thd)
71 {
72   if (!thd->in_sub_stmt)
73     thd->set_start_time();
74 }
75 
76 
77 Item::Type
78 sp_map_item_type(const Type_handler *handler)
79 {
80   if (handler == &type_handler_row)
81     return Item::ROW_ITEM;
82   enum_field_types type= real_type_to_type(handler->real_field_type());
83 
84   switch (type) {
85   case MYSQL_TYPE_BIT:
86   case MYSQL_TYPE_TINY:
87   case MYSQL_TYPE_SHORT:
88   case MYSQL_TYPE_LONG:
89   case MYSQL_TYPE_LONGLONG:
90   case MYSQL_TYPE_INT24:
91     return Item::INT_ITEM;
92   case MYSQL_TYPE_DECIMAL:
93   case MYSQL_TYPE_NEWDECIMAL:
94     return Item::DECIMAL_ITEM;
95   case MYSQL_TYPE_FLOAT:
96   case MYSQL_TYPE_DOUBLE:
97     return Item::REAL_ITEM;
98   default:
99     return Item::STRING_ITEM;
100   }
101 }
102 
103 
104 bool Item_splocal::append_for_log(THD *thd, String *str)
105 {
106   if (fix_fields_if_needed(thd, NULL))
107     return true;
108 
109   if (limit_clause_param)
110     return str->append_ulonglong(val_uint());
drop(self: ::pin_project::__private::Pin<&mut Self>)111 
112   /*
113     ROW variables are currently not allowed in select_list, e.g.:
114       SELECT row_variable;
115     ROW variables can appear in query parts where name is not important, e.g.:
116       SELECT ROW(1,2)=row_variable FROM t1;
117     So we can skip using NAME_CONST() and use ROW() constants directly.
118   */
119   if (type_handler() == &type_handler_row)
120     return append_value_for_log(thd, str);
121 
122   if (str->append(STRING_WITH_LEN(" NAME_CONST('")) ||
123       str->append(&m_name) ||
124       str->append(STRING_WITH_LEN("',")))
125     return true;
main()126   return append_value_for_log(thd, str) || str->append(')');
_is_unpin<T: Unpin>()127 }
128 
129 
130 bool Item_splocal::append_value_for_log(THD *thd, String *str)
131 {
132   StringBuffer<STRING_BUFFER_USUAL_SIZE> str_value_holder(&my_charset_latin1);
133   Item *item= this_item();
134   String *str_value= item->type_handler()->print_item_value(thd, item,
135                                                             &str_value_holder);
136   return str_value ?
137          str->append(*str_value) :
138          str->append(STRING_WITH_LEN("NULL"));
139 }
140 
141 
142 bool Item_splocal_row_field::append_for_log(THD *thd, String *str)
143 {
144   if (fix_fields_if_needed(thd, NULL))
145     return true;
146 
147   if (limit_clause_param)
148     return str->append_ulonglong(val_uint());
149 
150   if (str->append(STRING_WITH_LEN(" NAME_CONST('")) ||
151       str->append(&m_name) ||
152       str->append(".") ||
153       str->append(&m_field_name) ||
154       str->append(STRING_WITH_LEN("',")))
155     return true;
156   return append_value_for_log(thd, str) || str->append(')');
157 }
158 
159 
160 /**
161    Returns a combination of:
162    - sp_head::MULTI_RESULTS: added if the 'cmd' is a command that might
163      result in multiple result sets being sent back.
164    - sp_head::CONTAINS_DYNAMIC_SQL: added if 'cmd' is one of PREPARE,
165      EXECUTE, DEALLOCATE.
166 */
167 
168 uint
169 sp_get_flags_for_command(LEX *lex)
170 {
171   uint flags;
172 
173   switch (lex->sql_command) {
174   case SQLCOM_SELECT:
175     if (lex->result && !lex->analyze_stmt)
176     {
177       flags= 0;                      /* This is a SELECT with INTO clause */
178       break;
179     }
180     /* fallthrough */
181   case SQLCOM_ANALYZE:
182   case SQLCOM_OPTIMIZE:
183   case SQLCOM_PRELOAD_KEYS:
184   case SQLCOM_ASSIGN_TO_KEYCACHE:
185   case SQLCOM_CHECKSUM:
186   case SQLCOM_CHECK:
187   case SQLCOM_HA_READ:
188   case SQLCOM_SHOW_AUTHORS:
189   case SQLCOM_SHOW_BINLOGS:
190   case SQLCOM_SHOW_BINLOG_EVENTS:
191   case SQLCOM_SHOW_RELAYLOG_EVENTS:
192   case SQLCOM_SHOW_CHARSETS:
193   case SQLCOM_SHOW_COLLATIONS:
194   case SQLCOM_SHOW_CONTRIBUTORS:
195   case SQLCOM_SHOW_CREATE:
196   case SQLCOM_SHOW_CREATE_DB:
197   case SQLCOM_SHOW_CREATE_FUNC:
198   case SQLCOM_SHOW_CREATE_PROC:
199   case SQLCOM_SHOW_CREATE_PACKAGE:
200   case SQLCOM_SHOW_CREATE_PACKAGE_BODY:
201   case SQLCOM_SHOW_CREATE_EVENT:
202   case SQLCOM_SHOW_CREATE_TRIGGER:
203   case SQLCOM_SHOW_CREATE_USER:
204   case SQLCOM_SHOW_DATABASES:
205   case SQLCOM_SHOW_ERRORS:
206   case SQLCOM_SHOW_EXPLAIN:
207   case SQLCOM_SHOW_FIELDS:
208   case SQLCOM_SHOW_FUNC_CODE:
209   case SQLCOM_SHOW_GENERIC:
210   case SQLCOM_SHOW_GRANTS:
211   case SQLCOM_SHOW_ENGINE_STATUS:
212   case SQLCOM_SHOW_ENGINE_LOGS:
213   case SQLCOM_SHOW_ENGINE_MUTEX:
214   case SQLCOM_SHOW_EVENTS:
215   case SQLCOM_SHOW_KEYS:
216   case SQLCOM_SHOW_MASTER_STAT:
217   case SQLCOM_SHOW_OPEN_TABLES:
218   case SQLCOM_SHOW_PRIVILEGES:
219   case SQLCOM_SHOW_PROCESSLIST:
220   case SQLCOM_SHOW_PROC_CODE:
221   case SQLCOM_SHOW_PACKAGE_BODY_CODE:
222   case SQLCOM_SHOW_SLAVE_HOSTS:
223   case SQLCOM_SHOW_SLAVE_STAT:
224   case SQLCOM_SHOW_STATUS:
225   case SQLCOM_SHOW_STATUS_FUNC:
226   case SQLCOM_SHOW_STATUS_PROC:
227   case SQLCOM_SHOW_STATUS_PACKAGE:
228   case SQLCOM_SHOW_STATUS_PACKAGE_BODY:
229   case SQLCOM_SHOW_STORAGE_ENGINES:
230   case SQLCOM_SHOW_TABLES:
231   case SQLCOM_SHOW_TABLE_STATUS:
232   case SQLCOM_SHOW_VARIABLES:
233   case SQLCOM_SHOW_WARNS:
234   case SQLCOM_REPAIR:
235     flags= sp_head::MULTI_RESULTS;
236     break;
237   /*
238     EXECUTE statement may return a result set, but doesn't have to.
239     We can't, however, know it in advance, and therefore must add
240     this statement here. This is ok, as is equivalent to a result-set
241     statement within an IF condition.
242   */
243   case SQLCOM_EXECUTE:
244   case SQLCOM_EXECUTE_IMMEDIATE:
245     flags= sp_head::MULTI_RESULTS | sp_head::CONTAINS_DYNAMIC_SQL;
246     break;
247   case SQLCOM_PREPARE:
248   case SQLCOM_DEALLOCATE_PREPARE:
249     flags= sp_head::CONTAINS_DYNAMIC_SQL;
250     break;
251   case SQLCOM_CREATE_TABLE:
252   case SQLCOM_CREATE_SEQUENCE:
253     if (lex->tmp_table())
254       flags= 0;
255     else
256       flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
257     break;
258   case SQLCOM_DROP_TABLE:
259   case SQLCOM_DROP_SEQUENCE:
260     if (lex->tmp_table())
261       flags= 0;
262     else
263       flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
264     break;
265   case SQLCOM_FLUSH:
266     flags= sp_head::HAS_SQLCOM_FLUSH;
267     break;
268   case SQLCOM_RESET:
269     flags= sp_head::HAS_SQLCOM_RESET;
270     break;
271   case SQLCOM_CREATE_INDEX:
272   case SQLCOM_CREATE_DB:
273   case SQLCOM_CREATE_PACKAGE:
274   case SQLCOM_CREATE_PACKAGE_BODY:
275   case SQLCOM_CREATE_VIEW:
276   case SQLCOM_CREATE_TRIGGER:
277   case SQLCOM_CREATE_USER:
278   case SQLCOM_CREATE_ROLE:
279   case SQLCOM_ALTER_TABLE:
280   case SQLCOM_ALTER_SEQUENCE:
281   case SQLCOM_ALTER_USER:
282   case SQLCOM_GRANT:
283   case SQLCOM_GRANT_ROLE:
284   case SQLCOM_REVOKE:
285   case SQLCOM_REVOKE_ROLE:
286   case SQLCOM_BEGIN:
287   case SQLCOM_RENAME_TABLE:
288   case SQLCOM_RENAME_USER:
289   case SQLCOM_DROP_INDEX:
290   case SQLCOM_DROP_DB:
291   case SQLCOM_DROP_PACKAGE:
292   case SQLCOM_DROP_PACKAGE_BODY:
293   case SQLCOM_REVOKE_ALL:
294   case SQLCOM_DROP_USER:
295   case SQLCOM_DROP_ROLE:
296   case SQLCOM_DROP_VIEW:
297   case SQLCOM_DROP_TRIGGER:
298   case SQLCOM_TRUNCATE:
299   case SQLCOM_COMMIT:
300   case SQLCOM_ROLLBACK:
301   case SQLCOM_LOAD:
302   case SQLCOM_LOCK_TABLES:
303   case SQLCOM_CREATE_PROCEDURE:
304   case SQLCOM_CREATE_SPFUNCTION:
305   case SQLCOM_ALTER_PROCEDURE:
306   case SQLCOM_ALTER_FUNCTION:
307   case SQLCOM_DROP_PROCEDURE:
308   case SQLCOM_DROP_FUNCTION:
309   case SQLCOM_CREATE_EVENT:
310   case SQLCOM_ALTER_EVENT:
311   case SQLCOM_DROP_EVENT:
312   case SQLCOM_INSTALL_PLUGIN:
313   case SQLCOM_UNINSTALL_PLUGIN:
314     flags= sp_head::HAS_COMMIT_OR_ROLLBACK;
315     break;
316   case SQLCOM_DELETE:
317   case SQLCOM_DELETE_MULTI:
318   {
319     /*
320       DELETE normally doesn't return resultset, but there are 3 exceptions:
321        - DELETE ... RETURNING
322        - EXPLAIN DELETE ...
323        - ANALYZE DELETE ...
324     */
325     if (lex->select_lex.item_list.is_empty() &&
326         !lex->describe && !lex->analyze_stmt)
327       flags= 0;
328     else
329       flags= sp_head::MULTI_RESULTS;
330     break;
331   }
332   case SQLCOM_UPDATE:
333   case SQLCOM_UPDATE_MULTI:
334   case SQLCOM_INSERT:
335   case SQLCOM_REPLACE:
336   case SQLCOM_REPLACE_SELECT:
337   case SQLCOM_INSERT_SELECT:
338   {
339     if (!lex->describe && !lex->analyze_stmt)
340       flags= 0;
341     else
342       flags= sp_head::MULTI_RESULTS;
343     break;
344   }
345   default:
346     flags= 0;
347     break;
348   }
349   return flags;
350 }
351 
352 /**
353   Prepare an Item for evaluation (call of fix_fields).
354 
355   @param it_addr   pointer on item refernce
356   @param cols      expected number of elements (1 for scalar, >=1 for ROWs)
357 
358   @retval
359     NULL      error
360   @retval
361     non-NULL  prepared item
362 */
363 
364 Item *THD::sp_prepare_func_item(Item **it_addr, uint cols)
365 {
366   DBUG_ENTER("THD::sp_prepare_func_item");
367   Item *res= sp_fix_func_item(it_addr);
368   if (res && res->check_cols(cols))
369     DBUG_RETURN(NULL);
370   DBUG_RETURN(res);
371 }
372 
373 
374 /**
375   Fix an Item for evaluation for SP.
376 */
377 
378 Item *THD::sp_fix_func_item(Item **it_addr)
379 {
380   DBUG_ENTER("THD::sp_fix_func_item");
381   if ((*it_addr)->fix_fields_if_needed(this, it_addr))
382   {
383     DBUG_PRINT("info", ("fix_fields() failed"));
384     DBUG_RETURN(NULL);
385   }
386   it_addr= (*it_addr)->this_item_addr(this, it_addr);
387 
388   if ((*it_addr)->fix_fields_if_needed(this, it_addr))
389   {
390     DBUG_PRINT("info", ("fix_fields() failed"));
391     DBUG_RETURN(NULL);
392   }
393   DBUG_RETURN(*it_addr);
394 }
395 
396 
397 /**
398   Evaluate an expression and store the result in the field.
399 
400   @param result_field           the field to store the result
401   @param expr_item_ptr          the root item of the expression
402 
403   @retval
404     FALSE  on success
405   @retval
406     TRUE   on error
407 */
408 
409 bool THD::sp_eval_expr(Field *result_field, Item **expr_item_ptr)
410 {
411   DBUG_ENTER("THD::sp_eval_expr");
412   DBUG_ASSERT(*expr_item_ptr);
413   Sp_eval_expr_state state(this);
414   /* Save the value in the field. Convert the value if needed. */
415   DBUG_RETURN(result_field->sp_prepare_and_store_item(this, expr_item_ptr));
416 }
417 
418 
419 /**
420   Create temporary sp_name object from MDL key.
421 
422   @note The lifetime of this object is bound to the lifetime of the MDL_key.
423         This should be fine as sp_name objects created by this constructor
424         are mainly used for SP-cache lookups.
425 
426   @param key         MDL key containing database and routine name.
427   @param qname_buff  Buffer to be used for storing quoted routine name
428                      (should be at least 2*NAME_LEN+1+1 bytes).
429 */
430 
431 sp_name::sp_name(const MDL_key *key, char *qname_buff)
432  :Database_qualified_name(key->db_name(), key->db_name_length(),
433                           key->name(),  key->name_length()),
434   m_explicit_name(false)
435 {
436   if (m_db.length)
437     strxmov(qname_buff, m_db.str, ".", m_name.str, NullS);
438   else
439     strmov(qname_buff, m_name.str);
440 }
441 
442 
443 /**
444   Check that the name 'ident' is ok.  It's assumed to be an 'ident'
445   from the parser, so we only have to check length and trailing spaces.
446   The former is a standard requirement (and 'show status' assumes a
447   non-empty name), the latter is a mysql:ism as trailing spaces are
448   removed by get_field().
449 
450   @retval
451     TRUE    bad name
452   @retval
453     FALSE   name is ok
454 */
455 
456 bool
457 check_routine_name(const LEX_CSTRING *ident)
458 {
459   DBUG_ASSERT(ident);
460   DBUG_ASSERT(ident->str);
461 
462   if (!ident->str[0] || ident->str[ident->length-1] == ' ')
463   {
464     my_error(ER_SP_WRONG_NAME, MYF(0), ident->str);
465     return TRUE;
466   }
467   if (check_ident_length(ident))
468     return TRUE;
469 
470   return FALSE;
471 }
472 
473 
474 /*
475  *
476  *  sp_head
477  *
478  */
479 
480 sp_head *sp_head::create(sp_package *parent, const Sp_handler *handler)
481 {
482   MEM_ROOT own_root;
483   init_sql_alloc(&own_root, "sp_head", MEM_ROOT_BLOCK_SIZE, MEM_ROOT_PREALLOC,
484                  MYF(0));
485   sp_head *sp;
486   if (!(sp= new (&own_root) sp_head(&own_root, parent, handler)))
487     free_root(&own_root, MYF(0));
488 
489   return sp;
490 }
491 
492 
493 void sp_head::destroy(sp_head *sp)
494 {
495   if (sp)
496   {
497     /* Make a copy of main_mem_root as free_root will free the sp */
498     MEM_ROOT own_root= sp->main_mem_root;
499     DBUG_PRINT("info", ("mem_root %p moved to %p",
500                         &sp->mem_root, &own_root));
501     delete sp;
502 
503 
504     free_root(&own_root, MYF(0));
505   }
506 }
507 
508 /*
509  *
510  *  sp_head
511  *
512  */
513 
514 sp_head::sp_head(MEM_ROOT *mem_root_arg, sp_package *parent,
515                  const Sp_handler *sph)
516   :Query_arena(NULL, STMT_INITIALIZED_FOR_SP),
517    Database_qualified_name(&null_clex_str, &null_clex_str),
518    main_mem_root(*mem_root_arg),
519    m_parent(parent),
520    m_handler(sph),
521    m_flags(0),
522    m_tmp_query(NULL),
523    m_explicit_name(false),
524    /*
525      FIXME: the only use case when name is NULL is events, and it should
526      be rewritten soon. Remove the else part and replace 'if' with
527      an assert when this is done.
528    */
529    m_qname(null_clex_str),
530    m_params(null_clex_str),
531    m_body(null_clex_str),
532    m_body_utf8(null_clex_str),
533    m_defstr(null_clex_str),
534    m_sp_cache_version(0),
535    m_creation_ctx(0),
536    unsafe_flags(0),
537    m_created(0),
538    m_modified(0),
539    m_recursion_level(0),
540    m_next_cached_sp(0),
541    m_param_begin(NULL),
542    m_param_end(NULL),
543    m_body_begin(NULL),
544    m_thd_root(NULL),
545    m_thd(NULL),
546    m_pcont(new (&main_mem_root) sp_pcontext()),
547    m_cont_level(0)
548 {
549   mem_root= &main_mem_root;
550 
551   m_first_instance= this;
552   m_first_free_instance= this;
553   m_last_cached_sp= this;
554 
555   m_return_field_def.charset = NULL;
556 
557   DBUG_ENTER("sp_head::sp_head");
558 
559   m_security_ctx.init();
560   m_backpatch.empty();
561   m_backpatch_goto.empty();
562   m_cont_backpatch.empty();
563   m_lex.empty();
564   my_init_dynamic_array(&m_instr, sizeof(sp_instr *), 16, 8, MYF(0));
565   my_hash_init(&m_sptabs, system_charset_info, 0, 0, 0, sp_table_key, 0, 0);
566   my_hash_init(&m_sroutines, system_charset_info, 0, 0, 0, sp_sroutine_key,
567                0, 0);
568 
569   DBUG_VOID_RETURN;
570 }
571 
572 
573 sp_package *sp_package::create(LEX *top_level_lex, const sp_name *name,
574                                const Sp_handler *sph)
575 {
576   MEM_ROOT own_root;
577   init_sql_alloc(&own_root, "sp_package", MEM_ROOT_BLOCK_SIZE,
578                  MEM_ROOT_PREALLOC, MYF(0));
579   sp_package *sp;
580   if (!(sp= new (&own_root) sp_package(&own_root, top_level_lex, name, sph)))
581     free_root(&own_root, MYF(0));
582 
583   return sp;
584 }
585 
586 
587 sp_package::sp_package(MEM_ROOT *mem_root_arg,
588                        LEX *top_level_lex,
589                        const sp_name *name,
590                        const Sp_handler *sph)
591  :sp_head(mem_root_arg, NULL, sph),
592   m_current_routine(NULL),
593   m_top_level_lex(top_level_lex),
594   m_rcontext(NULL),
595   m_invoked_subroutine_count(0),
596   m_is_instantiated(false),
597   m_is_cloning_routine(false)
598 {
599   init_sp_name(name);
600 }
601 
602 
603 sp_package::~sp_package()
604 {
605   m_routine_implementations.cleanup();
606   m_routine_declarations.cleanup();
607   m_body= null_clex_str;
608   if (m_current_routine)
609     sp_head::destroy(m_current_routine->sphead);
610   delete m_rcontext;
611 }
612 
613 
614 /*
615   Test if two routines have equal specifications
616 */
617 
618 bool sp_head::eq_routine_spec(const sp_head *sp) const
619 {
620   // TODO: Add tests for equal return data types (in case of FUNCTION)
621   // TODO: Add tests for equal argument data types
622   return
623     m_handler->type() == sp->m_handler->type() &&
624     m_pcont->context_var_count() == sp->m_pcont->context_var_count();
625 }
626 
627 
628 bool sp_package::validate_after_parser(THD *thd)
629 {
630   if (m_handler->type() != TYPE_ENUM_PACKAGE_BODY)
631     return false;
632   sp_head *sp= sp_cache_lookup(&thd->sp_package_spec_cache, this);
633   sp_package *spec= sp ? sp->get_package() : NULL;
634   DBUG_ASSERT(spec); // CREATE PACKAGE must already be cached
635   return validate_public_routines(thd, spec) ||
636          validate_private_routines(thd);
637 }
638 
639 
640 bool sp_package::validate_public_routines(THD *thd, sp_package *spec)
641 {
642   /*
643     Check that all routines declared in CREATE PACKAGE
644     have implementations in CREATE PACKAGE BODY.
645   */
646   List_iterator<LEX> it(spec->m_routine_declarations);
647   for (LEX *lex; (lex= it++); )
648   {
649     bool found= false;
650     DBUG_ASSERT(lex->sphead);
651     List_iterator<LEX> it2(m_routine_implementations);
652     for (LEX *lex2; (lex2= it2++); )
653     {
654       DBUG_ASSERT(lex2->sphead);
655       if (Sp_handler::eq_routine_name(lex2->sphead->m_name,
656                                       lex->sphead->m_name) &&
657           lex2->sphead->eq_routine_spec(lex->sphead))
658       {
659         found= true;
660         break;
661       }
662     }
663     if (!found)
664     {
665       my_error(ER_PACKAGE_ROUTINE_IN_SPEC_NOT_DEFINED_IN_BODY, MYF(0),
666                ErrConvDQName(lex->sphead).ptr());
667       return true;
668     }
669   }
670   return false;
671 }
672 
673 
674 bool sp_package::validate_private_routines(THD *thd)
675 {
676   /*
677     Check that all forwad declarations in
678     CREATE PACKAGE BODY have implementations.
679   */
680   List_iterator<LEX> it(m_routine_declarations);
681   for (LEX *lex; (lex= it++); )
682   {
683     bool found= false;
684     DBUG_ASSERT(lex->sphead);
685     List_iterator<LEX> it2(m_routine_implementations);
686     for (LEX *lex2; (lex2= it2++); )
687     {
688       DBUG_ASSERT(lex2->sphead);
689       if (Sp_handler::eq_routine_name(lex2->sphead->m_name,
690                                       lex->sphead->m_name) &&
691           lex2->sphead->eq_routine_spec(lex->sphead))
692       {
693         found= true;
694         break;
695       }
696     }
697     if (!found)
698     {
699       my_error(ER_PACKAGE_ROUTINE_FORWARD_DECLARATION_NOT_DEFINED, MYF(0),
700                ErrConvDQName(lex->sphead).ptr());
701       return true;
702     }
703   }
704   return false;
705 }
706 
707 
708 LEX *sp_package::LexList::find(const LEX_CSTRING &name,
709                                stored_procedure_type type)
710 {
711   List_iterator<LEX> it(*this);
712   for (LEX *lex; (lex= it++); )
713   {
714     DBUG_ASSERT(lex->sphead);
715     const char *dot;
716     if (lex->sphead->m_handler->type() == type &&
717         (dot= strrchr(lex->sphead->m_name.str, '.')))
718     {
719       size_t ofs= dot + 1 - lex->sphead->m_name.str;
720       LEX_CSTRING non_qualified_sphead_name= lex->sphead->m_name;
721       non_qualified_sphead_name.str+= ofs;
722       non_qualified_sphead_name.length-= ofs;
723       if (Sp_handler::eq_routine_name(non_qualified_sphead_name, name))
724         return lex;
725     }
726   }
727   return NULL;
728 }
729 
730 
731 LEX *sp_package::LexList::find_qualified(const LEX_CSTRING &name,
732                                          stored_procedure_type type)
733 {
734   List_iterator<LEX> it(*this);
735   for (LEX *lex; (lex= it++); )
736   {
737     DBUG_ASSERT(lex->sphead);
738     if (lex->sphead->m_handler->type() == type &&
739         Sp_handler::eq_routine_name(lex->sphead->m_name, name))
740       return lex;
741   }
742   return NULL;
743 }
744 
745 
746 void
747 sp_head::init(LEX *lex)
748 {
749   DBUG_ENTER("sp_head::init");
750 
751   lex->spcont= m_pcont;
752 
753   if (!lex->spcont)
754     DBUG_VOID_RETURN;
755 
756   /*
757     Altough trg_table_fields list is used only in triggers we init for all
758     types of stored procedures to simplify reset_lex()/restore_lex() code.
759   */
760   lex->trg_table_fields.empty();
761 
762   DBUG_VOID_RETURN;
763 }
764 
765 
766 void
767 sp_head::init_sp_name(const sp_name *spname)
768 {
769   DBUG_ENTER("sp_head::init_sp_name");
770 
771   /* Must be initialized in the parser. */
772 
773   DBUG_ASSERT(spname && spname->m_db.str && spname->m_db.length);
774 
775   /* We have to copy strings to get them into the right memroot. */
776   Database_qualified_name::copy(&main_mem_root, spname->m_db, spname->m_name);
777   m_explicit_name= spname->m_explicit_name;
778   DBUG_VOID_RETURN;
779 }
780 
781 
782 void
783 sp_head::set_body_start(THD *thd, const char *begin_ptr)
784 {
785   m_body_begin= begin_ptr;
786   thd->m_parser_state->m_lip.body_utf8_start(thd, begin_ptr);
787 }
788 
789 
790 void
791 sp_head::set_stmt_end(THD *thd)
792 {
793   Lex_input_stream *lip= & thd->m_parser_state->m_lip; /* shortcut */
794   const char *end_ptr= lip->get_cpp_ptr(); /* shortcut */
795 
796   /* Make the string of parameters. */
797 
798   if (m_param_begin && m_param_end)
799   {
800     m_params.length= m_param_end - m_param_begin;
801     m_params.str= thd->strmake(m_param_begin, m_params.length);
802   }
803 
804   /* Remember end pointer for further dumping of whole statement. */
805 
806   thd->lex->stmt_definition_end= end_ptr;
807 
808   /* Make the string of body (in the original character set). */
809 
810   m_body.length= end_ptr - m_body_begin;
811   m_body.str= thd->strmake(m_body_begin, m_body.length);
812   trim_whitespace(thd->charset(), &m_body);
813 
814   /* Make the string of UTF-body. */
815 
816   lip->body_utf8_append(end_ptr);
817 
818   m_body_utf8.length= lip->get_body_utf8_length();
819   m_body_utf8.str= thd->strmake(lip->get_body_utf8_str(), m_body_utf8.length);
820   trim_whitespace(thd->charset(), &m_body_utf8);
821 
822   /*
823     Make the string of whole stored-program-definition query (in the
824     original character set).
825   */
826 
827   m_defstr.length= end_ptr - lip->get_cpp_buf();
828   m_defstr.str= thd->strmake(lip->get_cpp_buf(), m_defstr.length);
829   trim_whitespace(thd->charset(), &m_defstr);
830 }
831 
832 
833 sp_head::~sp_head()
834 {
835   LEX *lex;
836   sp_instr *i;
837   DBUG_ENTER("sp_head::~sp_head");
838 
839   /* sp_head::restore_thd_mem_root() must already have been called. */
840   DBUG_ASSERT(m_thd == NULL);
841 
842   for (uint ip = 0 ; (i = get_instr(ip)) ; ip++)
843     delete i;
844   delete_dynamic(&m_instr);
845   delete m_pcont;
846   free_items();
847 
848   /*
849     If we have non-empty LEX stack then we just came out of parser with
850     error. Now we should delete all auxilary LEXes and restore original
851     THD::lex. It is safe to not update LEX::ptr because further query
852     string parsing and execution will be stopped anyway.
853   */
854   while ((lex= (LEX *)m_lex.pop()))
855   {
856     THD *thd= lex->thd;
857     thd->lex->sphead= NULL;
858     lex_end(thd->lex);
859     delete thd->lex;
860     thd->lex= lex;
861   }
862 
863   my_hash_free(&m_sptabs);
864   my_hash_free(&m_sroutines);
865 
866   sp_head::destroy(m_next_cached_sp);
867 
868   DBUG_VOID_RETURN;
869 }
870 
871 
872 void sp_package::LexList::cleanup()
873 {
874   List_iterator<LEX> it(*this);
875   for (LEX *lex; (lex= it++); )
876   {
877     lex_end(lex);
878     delete lex;
879   }
880 }
881 
882 
883 /**
884   This is only used for result fields from functions (both during
885   fix_length_and_dec() and evaluation).
886 */
887 
888 Field *
889 sp_head::create_result_field(uint field_max_length, const LEX_CSTRING *field_name,
890                              TABLE *table) const
891 {
892   Field *field;
893   LEX_CSTRING name;
894 
895   DBUG_ENTER("sp_head::create_result_field");
896 
897   /*
898     m_return_field_def.length is always set to the field length calculated
899     by the parser, according to the RETURNS clause. See prepare_create_field()
900     in sql_table.cc. Value examples, depending on data type:
901     - 11 for INT                          (character representation length)
902     - 20 for BIGINT                       (character representation length)
903     - 22 for DOUBLE                       (character representation length)
904     - N for CHAR(N) CHARACTER SET latin1  (octet length)
905     - 3*N for CHAR(N) CHARACTER SET utf8  (octet length)
906     - 8 for blob-alike data types         (packed length !!!)
907 
908     field_max_length is also set according to the data type in the RETURNS
909     clause but can have different values depending on the execution stage:
910 
911     1. During direct execution:
912     field_max_length is 0, because Item_func_sp::fix_length_and_dec() has
913     not been called yet, so Item_func_sp::max_length is 0 by default.
914 
915     2a. During PREPARE:
916     field_max_length is 0, because Item_func_sp::fix_length_and_dec()
917     has not been called yet. It's called after create_result_field().
918 
919     2b. During EXEC:
920     field_max_length is set to the maximum possible octet length of the
921     RETURNS data type.
922     - N for CHAR(N) CHARACTER SET latin1  (octet length)
923     - 3*N for CHAR(N) CHARACTER SET utf8  (octet length)
924     - 255 for TINYBLOB                    (octet length, not packed length !!!)
925 
926     Perhaps we should refactor prepare_create_field() to set
927     Create_field::length to maximum octet length for BLOBs,
928     instead of packed length).
929 
930     Note, for integer data types, field_max_length can be bigger
931     than the user specified length, e.g. a field of the INT(1) data type
932     is translated to the item with max_length=11.
933   */
934   DBUG_ASSERT(field_max_length <= m_return_field_def.length ||
935               m_return_field_def.type_handler()->cmp_type() == INT_RESULT ||
936               (current_thd->stmt_arena->is_stmt_execute() &&
937                m_return_field_def.length == 8 &&
938                (m_return_field_def.pack_flag &
939                 (FIELDFLAG_BLOB|FIELDFLAG_GEOM))));
940 
941   if (field_name)
942     name= *field_name;
943   else
944     name= m_name;
945   field= m_return_field_def.make_field(table->s, /* TABLE_SHARE ptr */
946                                        table->in_use->mem_root,
947                                        &name);
948 
949   field->vcol_info= m_return_field_def.vcol_info;
950   if (field)
951     field->init(table);
952 
953   DBUG_RETURN(field);
954 }
955 
956 
957 int cmp_rqp_locations(Rewritable_query_parameter * const *a,
958                       Rewritable_query_parameter * const *b)
959 {
960   return (int)((*a)->pos_in_query - (*b)->pos_in_query);
961 }
962 
963 
964 /*
965   StoredRoutinesBinlogging
966   This paragraph applies only to statement-based binlogging. Row-based
967   binlogging does not need anything special like this.
968 
969   Top-down overview:
970 
971   1. Statements
972 
973   Statements that have is_update_query(stmt) == TRUE are written into the
974   binary log verbatim.
975   Examples:
976     UPDATE tbl SET tbl.x = spfunc_w_side_effects()
977     UPDATE tbl SET tbl.x=1 WHERE spfunc_w_side_effect_that_returns_false(tbl.y)
978 
979   Statements that have is_update_query(stmt) == FALSE (e.g. SELECTs) are not
980   written into binary log. Instead we catch function calls the statement
981   makes and write it into binary log separately (see #3).
982 
983   2. PROCEDURE calls
984 
985   CALL statements are not written into binary log. Instead
986   * Any FUNCTION invocation (in SET, IF, WHILE, OPEN CURSOR and other SP
987     instructions) is written into binlog separately.
988 
989   * Each statement executed in SP is binlogged separately, according to rules
990     in #1, with the exception that we modify query string: we replace uses
991     of SP local variables with NAME_CONST('spvar_name', <spvar-value>) calls.
992     This substitution is done in subst_spvars().
993 
994   3. FUNCTION calls
995 
996   In sp_head::execute_function(), we check
997    * If this function invocation is done from a statement that is written
998      into the binary log.
999    * If there were any attempts to write events to the binary log during
1000      function execution (grep for start_union_events and stop_union_events)
1001 
1002    If the answers are No and Yes, we write the function call into the binary
1003    log as "SELECT spfunc(<param1value>, <param2value>, ...)"
1004 
1005 
1006   4. Miscellaneous issues.
1007 
1008   4.1 User variables.
1009 
1010   When we call mysql_bin_log.write() for an SP statement, thd->user_var_events
1011   must hold set<{var_name, value}> pairs for all user variables used during
1012   the statement execution.
1013   This set is produced by tracking user variable reads during statement
1014   execution.
1015 
1016   For SPs, this has the following implications:
1017   1) thd->user_var_events may contain events from several SP statements and
1018      needs to be valid after exection of these statements was finished. In
1019      order to achieve that, we
1020      * Allocate user_var_events array elements on appropriate mem_root (grep
1021        for user_var_events_alloc).
1022      * Use is_query_in_union() to determine if user_var_event is created.
1023 
1024   2) We need to empty thd->user_var_events after we have wrote a function
1025      call. This is currently done by making
1026      reset_dynamic(&thd->user_var_events);
1027      calls in several different places. (TODO cosider moving this into
1028      mysql_bin_log.write() function)
1029 
1030   4.2 Auto_increment storage in binlog
1031 
1032   As we may write two statements to binlog from one single logical statement
1033   (case of "SELECT func1(),func2()": it is binlogged as "SELECT func1()" and
1034   then "SELECT func2()"), we need to reset auto_increment binlog variables
1035   after each binlogged SELECT. Otherwise, the auto_increment value of the
1036   first SELECT would be used for the second too.
1037 */
1038 
1039 
1040 /**
1041   Replace thd->query{_length} with a string that one can write to
1042   the binlog.
1043 
1044   The binlog-suitable string is produced by replacing references to SP local
1045   variables with NAME_CONST('sp_var_name', value) calls.
1046 
1047   @param thd        Current thread.
1048   @param instr      Instruction (we look for Item_splocal instances in
1049                     instr->free_list)
1050   @param query_str  Original query string
1051 
1052   @return
1053     - FALSE  on success.
1054     thd->query{_length} either has been appropriately replaced or there
1055     is no need for replacements.
1056     - TRUE   out of memory error.
1057 */
1058 
1059 static bool
1060 subst_spvars(THD *thd, sp_instr *instr, LEX_STRING *query_str)
1061 {
1062   DBUG_ENTER("subst_spvars");
1063 
1064   Dynamic_array<Rewritable_query_parameter*> rewritables;
1065   char *pbuf;
1066   StringBuffer<512> qbuf;
1067   Copy_query_with_rewrite acc(thd, query_str->str, query_str->length, &qbuf);
1068 
1069   /* Find rewritable Items used in this statement */
1070   for (Item *item= instr->free_list; item; item= item->next)
1071   {
1072     Rewritable_query_parameter *rqp= item->get_rewritable_query_parameter();
1073     if (rqp && rqp->pos_in_query)
1074       rewritables.append(rqp);
1075   }
1076   if (!rewritables.elements())
1077     DBUG_RETURN(FALSE);
1078 
1079   rewritables.sort(cmp_rqp_locations);
1080 
1081   thd->query_name_consts= (uint)rewritables.elements();
1082 
1083   for (Rewritable_query_parameter **rqp= rewritables.front();
1084        rqp <= rewritables.back(); rqp++)
1085   {
1086     if (acc.append(*rqp))
1087       DBUG_RETURN(TRUE);
1088   }
1089   if (acc.finalize())
1090     DBUG_RETURN(TRUE);
1091 
1092   /*
1093     Allocate additional space at the end of the new query string for the
1094     query_cache_send_result_to_client function.
1095 
1096     The query buffer layout is:
1097        buffer :==
1098             <statement>   The input statement(s)
1099             '\0'          Terminating null char
1100             <length>      Length of following current database name 2
1101             <db_name>     Name of current database
1102             <flags>       Flags struct
1103   */
1104   size_t buf_len= (qbuf.length() + 1 + QUERY_CACHE_DB_LENGTH_SIZE +
1105                 thd->db.length + QUERY_CACHE_FLAGS_SIZE + 1);
1106   if ((pbuf= (char *) alloc_root(thd->mem_root, buf_len)))
1107   {
1108     char *ptr= pbuf + qbuf.length();
1109     memcpy(pbuf, qbuf.ptr(), qbuf.length());
1110     *ptr= 0;
1111     int2store(ptr+1, thd->db.length);
1112   }
1113   else
1114     DBUG_RETURN(TRUE);
1115 
1116   thd->set_query(pbuf, qbuf.length());
1117 
1118   DBUG_RETURN(FALSE);
1119 }
1120 
1121 
1122 void Sp_handler_procedure::recursion_level_error(THD *thd,
1123                                                  const sp_head *sp) const
1124 {
1125   my_error(ER_SP_RECURSION_LIMIT, MYF(0),
1126            static_cast<int>(thd->variables.max_sp_recursion_depth),
1127            sp->m_name.str);
1128 }
1129 
1130 
1131 /**
1132   Execute the routine. The main instruction jump loop is there.
1133   Assume the parameters already set.
1134 
1135   @param thd                  Thread context.
1136   @param merge_da_on_success  Flag specifying if Warning Info should be
1137                               propagated to the caller on Completion
1138                               Condition or not.
1139 
1140   @todo
1141     - Will write this SP statement into binlog separately
1142     (TODO: consider changing the condition to "not inside event union")
1143 
1144   @return Error status.
1145   @retval
1146     FALSE  on success
1147   @retval
1148     TRUE   on error
1149 */
1150 
1151 bool
1152 sp_head::execute(THD *thd, bool merge_da_on_success)
1153 {
1154   DBUG_ENTER("sp_head::execute");
1155   char saved_cur_db_name_buf[SAFE_NAME_LEN+1];
1156   LEX_STRING saved_cur_db_name=
1157     { saved_cur_db_name_buf, sizeof(saved_cur_db_name_buf) };
1158   bool cur_db_changed= FALSE;
1159   sp_rcontext *ctx= thd->spcont;
1160   bool err_status= FALSE;
1161   uint ip= 0;
1162   sql_mode_t save_sql_mode;
1163 
1164   // TODO(cvicentiu) See if you can drop this bit. This is used to resume
1165   // execution from where we left off.
1166   if (m_chistics.agg_type == GROUP_AGGREGATE)
1167     ip= thd->spcont->instr_ptr;
1168 
1169   bool save_abort_on_warning;
1170   Query_arena *old_arena;
1171   /* per-instruction arena */
1172   MEM_ROOT execute_mem_root;
1173   Query_arena execute_arena(&execute_mem_root, STMT_INITIALIZED_FOR_SP),
1174               backup_arena;
1175   query_id_t old_query_id;
1176   TABLE *old_derived_tables;
1177   TABLE *old_rec_tables;
1178   LEX *old_lex;
1179   Item_change_list old_change_list;
1180   String old_packet;
1181   uint old_server_status;
1182   const uint status_backup_mask= SERVER_STATUS_CURSOR_EXISTS |
1183                                  SERVER_STATUS_LAST_ROW_SENT;
1184   MEM_ROOT *user_var_events_alloc_saved= 0;
1185   Reprepare_observer *save_reprepare_observer= thd->m_reprepare_observer;
1186   Object_creation_ctx *UNINIT_VAR(saved_creation_ctx);
1187   Diagnostics_area *da= thd->get_stmt_da();
1188   Warning_info sp_wi(da->warning_info_id(), false, true);
1189 
1190   /* this 7*STACK_MIN_SIZE is a complex matter with a long history (see it!) */
1191   if (check_stack_overrun(thd, 7 * STACK_MIN_SIZE, (uchar*)&old_packet))
1192     DBUG_RETURN(TRUE);
1193 
1194   /* init per-instruction memroot */
1195   init_sql_alloc(&execute_mem_root, "per_instruction_memroot",
1196                  MEM_ROOT_BLOCK_SIZE, 0, MYF(0));
1197 
1198   DBUG_ASSERT(!(m_flags & IS_INVOKED));
1199   m_flags|= IS_INVOKED;
1200   if (m_parent)
1201     m_parent->m_invoked_subroutine_count++;
1202   m_first_instance->m_first_free_instance= m_next_cached_sp;
1203   if (m_next_cached_sp)
1204   {
1205     DBUG_PRINT("info",
1206                ("first free for %p ++: %p->%p  level: %lu  flags %x",
1207                m_first_instance, this,
1208                 m_next_cached_sp,
1209                 m_next_cached_sp->m_recursion_level,
1210                 m_next_cached_sp->m_flags));
1211   }
1212   /*
1213     Check that if there are not any instances after this one then
1214     pointer to the last instance points on this instance or if there are
1215     some instances after this one then recursion level of next instance
1216     greater then recursion level of current instance on 1
1217   */
1218   DBUG_ASSERT((m_next_cached_sp == 0 &&
1219                m_first_instance->m_last_cached_sp == this) ||
1220               (m_recursion_level + 1 == m_next_cached_sp->m_recursion_level));
1221 
1222   /*
1223     NOTE: The SQL Standard does not specify the context that should be
1224     preserved for stored routines. However, at SAP/Walldorf meeting it was
1225     decided that current database should be preserved.
1226   */
1227 
1228   if (m_db.length &&
1229       (err_status= mysql_opt_change_db(thd, &m_db, &saved_cur_db_name, FALSE,
1230                                        &cur_db_changed)))
1231   {
1232     goto done;
1233   }
1234 
1235   thd->is_slave_error= 0;
1236   old_arena= thd->stmt_arena;
1237 
1238   /* Push a new warning information area. */
1239   da->copy_sql_conditions_to_wi(thd, &sp_wi);
1240   da->push_warning_info(&sp_wi);
1241 
1242   /*
1243     Switch query context. This has to be done early as this is sometimes
1244     allocated on THD::mem_root
1245   */
1246   if (m_creation_ctx)
1247     saved_creation_ctx= m_creation_ctx->set_n_backup(thd);
1248 
1249   /*
1250     We have to save/restore this info when we are changing call level to
1251     be able properly do close_thread_tables() in instructions.
1252   */
1253   old_query_id= thd->query_id;
1254   old_derived_tables= thd->derived_tables;
1255   thd->derived_tables= 0;
1256   old_rec_tables= thd->rec_tables;
1257   thd->rec_tables= 0;
1258   save_sql_mode= thd->variables.sql_mode;
1259   thd->variables.sql_mode= m_sql_mode;
1260   save_abort_on_warning= thd->abort_on_warning;
1261   thd->abort_on_warning= 0;
1262   /**
1263     When inside a substatement (a stored function or trigger
1264     statement), clear the metadata observer in THD, if any.
1265     Remember the value of the observer here, to be able
1266     to restore it when leaving the substatement.
1267 
1268     We reset the observer to suppress errors when a substatement
1269     uses temporary tables. If a temporary table does not exist
1270     at start of the main statement, it's not prelocked
1271     and thus is not validated with other prelocked tables.
1272 
1273     Later on, when the temporary table is opened, metadata
1274     versions mismatch, expectedly.
1275 
1276     The proper solution for the problem is to re-validate tables
1277     of substatements (Bug#12257, Bug#27011, Bug#32868, Bug#33000),
1278     but it's not implemented yet.
1279   */
1280   thd->m_reprepare_observer= 0;
1281 
1282   /*
1283     It is also more efficient to save/restore current thd->lex once when
1284     do it in each instruction
1285   */
1286   old_lex= thd->lex;
1287   /*
1288     We should also save Item tree change list to avoid rollback something
1289     too early in the calling query.
1290   */
1291   thd->Item_change_list::move_elements_to(&old_change_list);
1292   /*
1293     Cursors will use thd->packet, so they may corrupt data which was prepared
1294     for sending by upper level. OTOH cursors in the same routine can share this
1295     buffer safely so let use use routine-local packet instead of having own
1296     packet buffer for each cursor.
1297 
1298     It is probably safe to use same thd->convert_buff everywhere.
1299   */
1300   old_packet.swap(thd->packet);
1301   old_server_status= thd->server_status & status_backup_mask;
1302 
1303   /*
1304     Switch to per-instruction arena here. We can do it since we cleanup
1305     arena after every instruction.
1306   */
1307   thd->set_n_backup_active_arena(&execute_arena, &backup_arena);
1308 
1309   /*
1310     Save callers arena in order to store instruction results and out
1311     parameters in it later during sp_eval_func_item()
1312   */
1313   thd->spcont->callers_arena= &backup_arena;
1314 
1315 #if defined(ENABLED_PROFILING)
1316   /* Discard the initial part of executing routines. */
1317   thd->profiling.discard_current_query();
1318 #endif
1319   sp_instr *i;
1320   DEBUG_SYNC(thd, "sp_head_execute_before_loop");
1321   do
1322   {
1323 #if defined(ENABLED_PROFILING)
1324     /*
1325      Treat each "instr" of a routine as discrete unit that could be profiled.
1326      Profiling only records information for segments of code that set the
1327      source of the query, and almost all kinds of instructions in s-p do not.
1328     */
1329     thd->profiling.finish_current_query();
1330     thd->profiling.start_new_query("continuing inside routine");
1331 #endif
1332 
1333     /* get_instr returns NULL when we're done. */
1334     i = get_instr(ip);
1335     if (i == NULL)
1336     {
1337 #if defined(ENABLED_PROFILING)
1338       thd->profiling.discard_current_query();
1339 #endif
1340       thd->spcont->quit_func= TRUE;
1341       break;
1342     }
1343 
1344     /* Reset number of warnings for this query. */
1345     thd->get_stmt_da()->reset_for_next_command();
1346 
1347     DBUG_PRINT("execute", ("Instruction %u", ip));
1348 
1349     /*
1350       We need to reset start_time to allow for time to flow inside a stored
1351       procedure. This is only done for SP since time is suppose to be constant
1352       during execution of triggers and functions.
1353     */
1354     reset_start_time_for_sp(thd);
1355 
1356     /*
1357       We have to set thd->stmt_arena before executing the instruction
1358       to store in the instruction free_list all new items, created
1359       during the first execution (for example expanding of '*' or the
1360       items made during other permanent subquery transformations).
1361     */
1362     thd->stmt_arena= i;
1363 
1364     /*
1365       Will write this SP statement into binlog separately.
1366       TODO: consider changing the condition to "not inside event union".
1367     */
1368     if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
1369     {
1370       user_var_events_alloc_saved= thd->user_var_events_alloc;
1371       thd->user_var_events_alloc= thd->mem_root;
1372     }
1373 
1374     sql_digest_state *parent_digest= thd->m_digest;
1375     thd->m_digest= NULL;
1376 
1377     err_status= i->execute(thd, &ip);
1378 #ifdef WITH_WSREP
1379     if (m_handler->type() == TYPE_ENUM_PROCEDURE)
1380     {
1381       mysql_mutex_lock(&thd->LOCK_thd_data);
1382       if (thd->wsrep_conflict_state == MUST_REPLAY)
1383       {
1384         wsrep_replay_sp_transaction(thd);
1385         err_status= thd->get_stmt_da()->is_set();
1386         thd->wsrep_conflict_state= NO_CONFLICT;
1387       }
1388       else if (thd->wsrep_conflict_state == ABORTED ||
1389                thd->wsrep_conflict_state == CERT_FAILURE)
1390       {
1391         /*
1392           If the statement execution was BF aborted or was aborted
1393           due to certification failure, clean up transaction here
1394           and reset conflict state to NO_CONFLICT and thd->killed
1395           to THD::NOT_KILLED. Error handling is done based on err_status
1396           below. Error must have been raised by wsrep hton code before
1397           entering here.
1398          */
1399         DBUG_ASSERT(err_status);
1400         DBUG_ASSERT(thd->get_stmt_da()->is_error());
1401         thd->wsrep_conflict_state= NO_CONFLICT;
1402         thd->killed= NOT_KILLED;
1403       }
1404       mysql_mutex_unlock(&thd->LOCK_thd_data);
1405     }
1406 #endif /* WITH_WSREP */
1407 #ifdef WITH_WSREP_NO
1408     if (WSREP(thd))
1409     {
1410       if (((thd->wsrep_trx().state() == wsrep::transaction::s_executing) &&
1411            (thd->is_fatal_error || thd->killed)))
1412       {
1413         WSREP_DEBUG("SP abort err status %d in sub %d trx state %d",
1414                     err_status, thd->in_sub_stmt, thd->wsrep_trx().state());
1415         err_status= 1;
1416         thd->is_fatal_error= 1;
1417         /*
1418           SP was killed, and it is not due to a wsrep conflict.
1419           We skip after_command hook at this point because
1420           otherwise it clears the error, and cleans up the
1421           whole transaction. For now we just return and finish
1422           our handling once we are back to mysql_parse.
1423         */
1424         WSREP_DEBUG("Skipping after_command hook for killed SP");
1425       }
1426       else
1427       {
1428         const bool must_replay= wsrep_must_replay(thd);
1429         if (must_replay)
1430         {
1431           WSREP_DEBUG("MUST_REPLAY set after SP, err_status %d trx state: %d",
1432                       err_status, thd->wsrep_trx().state());
1433         }
1434         (void) wsrep_after_statement(thd);
1435 
1436         /*
1437           Reset the return code to zero if the transaction was
1438           replayed succesfully.
1439         */
1440         if (must_replay && !wsrep_current_error(thd))
1441         {
1442           err_status= 0;
1443           thd->get_stmt_da()->reset_diagnostics_area();
1444         }
1445         /*
1446           Final wsrep error status for statement is known only after
1447           wsrep_after_statement() call. If the error is set, override
1448           error in thd diagnostics area and reset wsrep client_state error
1449           so that the error does not get propagated via client-server protocol.
1450         */
1451         if (wsrep_current_error(thd))
1452         {
1453           wsrep_override_error(thd, wsrep_current_error(thd),
1454                                wsrep_current_error_status(thd));
1455           thd->wsrep_cs().reset_error();
1456           /* Reset also thd->killed if it has been set during BF abort. */
1457           if (thd->killed == KILL_QUERY)
1458             thd->killed= NOT_KILLED;
1459           /* if failed transaction was not replayed, must return with error from here */
1460           if (!must_replay) err_status = 1;
1461         }
1462       }
1463     }
1464 #endif /* WITH_WSREP */
1465     thd->m_digest= parent_digest;
1466 
1467     if (i->free_list)
1468       cleanup_items(i->free_list);
1469 
1470     /*
1471       If we've set thd->user_var_events_alloc to mem_root of this SP
1472       statement, clean all the events allocated in it.
1473     */
1474     if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
1475     {
1476       reset_dynamic(&thd->user_var_events);
1477       thd->user_var_events_alloc= user_var_events_alloc_saved;
1478     }
1479 
1480     /* we should cleanup free_list and memroot, used by instruction */
1481     thd->cleanup_after_query();
1482     free_root(&execute_mem_root, MYF(0));
1483 
1484     /*
1485       Find and process SQL handlers unless it is a fatal error (fatal
1486       errors are not catchable by SQL handlers) or the connection has been
1487       killed during execution.
1488     */
1489     if (likely(!thd->is_fatal_error) && likely(!thd->killed_errno()) &&
1490         ctx->handle_sql_condition(thd, &ip, i))
1491     {
1492       err_status= FALSE;
1493     }
1494 
1495     /* Reset sp_rcontext::end_partial_result_set flag. */
1496     ctx->end_partial_result_set= FALSE;
1497 
1498   } while (!err_status && likely(!thd->killed) &&
1499            likely(!thd->is_fatal_error) &&
1500            !thd->spcont->pause_state);
1501 
1502 #if defined(ENABLED_PROFILING)
1503   thd->profiling.finish_current_query();
1504   thd->profiling.start_new_query("tail end of routine");
1505 #endif
1506 
1507   /* Restore query context. */
1508 
1509   if (m_creation_ctx)
1510     m_creation_ctx->restore_env(thd, saved_creation_ctx);
1511 
1512   /* Restore arena. */
1513 
1514   thd->restore_active_arena(&execute_arena, &backup_arena);
1515 
1516   /* Only pop cursors when we're done with group aggregate running. */
1517   if (m_chistics.agg_type != GROUP_AGGREGATE ||
1518       (m_chistics.agg_type == GROUP_AGGREGATE && thd->spcont->quit_func))
1519     thd->spcont->pop_all_cursors(thd); // To avoid memory leaks after an error
1520 
1521   /* Restore all saved */
1522   if (m_chistics.agg_type == GROUP_AGGREGATE)
1523     thd->spcont->instr_ptr= ip;
1524   thd->server_status= (thd->server_status & ~status_backup_mask) | old_server_status;
1525   old_packet.swap(thd->packet);
1526   DBUG_ASSERT(thd->Item_change_list::is_empty());
1527   old_change_list.move_elements_to(thd);
1528   thd->lex= old_lex;
1529   thd->set_query_id(old_query_id);
1530   DBUG_ASSERT(!thd->derived_tables);
1531   thd->derived_tables= old_derived_tables;
1532   thd->rec_tables= old_rec_tables;
1533   thd->variables.sql_mode= save_sql_mode;
1534   thd->abort_on_warning= save_abort_on_warning;
1535   thd->m_reprepare_observer= save_reprepare_observer;
1536 
1537   thd->stmt_arena= old_arena;
1538   state= STMT_EXECUTED;
1539 
1540   /*
1541     Restore the caller's original warning information area:
1542       - warnings generated during trigger execution should not be
1543         propagated to the caller on success;
1544       - if there was an exception during execution, warning info should be
1545         propagated to the caller in any case.
1546   */
1547   da->pop_warning_info();
1548 
1549   if (err_status || merge_da_on_success)
1550   {
1551     /*
1552       If a routine body is empty or if a routine did not generate any warnings,
1553       do not duplicate our own contents by appending the contents of the called
1554       routine. We know that the called routine did not change its warning info.
1555 
1556       On the other hand, if the routine body is not empty and some statement in
1557       the routine generates a warning or uses tables, warning info is guaranteed
1558       to have changed. In this case we know that the routine warning info
1559       contains only new warnings, and thus we perform a copy.
1560     */
1561     if (da->warning_info_changed(&sp_wi))
1562     {
1563       /*
1564         If the invocation of the routine was a standalone statement,
1565         rather than a sub-statement, in other words, if it's a CALL
1566         of a procedure, rather than invocation of a function or a
1567         trigger, we need to clear the current contents of the caller's
1568         warning info.
1569 
1570         This is per MySQL rules: if a statement generates a warning,
1571         warnings from the previous statement are flushed.  Normally
1572         it's done in push_warning(). However, here we don't use
1573         push_warning() to avoid invocation of condition handlers or
1574         escalation of warnings to errors.
1575       */
1576       da->opt_clear_warning_info(thd->query_id);
1577       da->copy_sql_conditions_from_wi(thd, &sp_wi);
1578       da->remove_marked_sql_conditions();
1579       if (i != NULL)
1580         push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE,
1581                             ER_SP_STACK_TRACE,
1582                             ER_THD(thd, ER_SP_STACK_TRACE),
1583                             i->m_lineno,
1584                             m_qname.str != NULL ? m_qname.str :
1585                                                   "anonymous block");
1586     }
1587   }
1588 
1589  done:
1590   DBUG_PRINT("info", ("err_status: %d  killed: %d  is_slave_error: %d  report_error: %d",
1591                       err_status, thd->killed, thd->is_slave_error,
1592                       thd->is_error()));
1593 
1594   if (thd->killed)
1595     err_status= TRUE;
1596   /*
1597     If the DB has changed, the pointer has changed too, but the
1598     original thd->db will then have been freed
1599   */
1600   if (cur_db_changed && thd->killed != KILL_CONNECTION)
1601   {
1602     /*
1603       Force switching back to the saved current database, because it may be
1604       NULL. In this case, mysql_change_db() would generate an error.
1605     */
1606 
1607     err_status|= mysql_change_db(thd, (LEX_CSTRING*)&saved_cur_db_name, TRUE) != 0;
1608   }
1609   m_flags&= ~IS_INVOKED;
1610   if (m_parent)
1611     m_parent->m_invoked_subroutine_count--;
1612   DBUG_PRINT("info",
1613              ("first free for %p --: %p->%p, level: %lu, flags %x",
1614               m_first_instance,
1615               m_first_instance->m_first_free_instance,
1616               this, m_recursion_level, m_flags));
1617   /*
1618     Check that we have one of following:
1619 
1620     1) there are not free instances which means that this instance is last
1621     in the list of instances (pointer to the last instance point on it and
1622     ther are not other instances after this one in the list)
1623 
1624     2) There are some free instances which mean that first free instance
1625     should go just after this one and recursion level of that free instance
1626     should be on 1 more then recursion level of this instance.
1627   */
1628   DBUG_ASSERT((m_first_instance->m_first_free_instance == 0 &&
1629                this == m_first_instance->m_last_cached_sp &&
1630                m_next_cached_sp == 0) ||
1631               (m_first_instance->m_first_free_instance != 0 &&
1632                m_first_instance->m_first_free_instance == m_next_cached_sp &&
1633                m_first_instance->m_first_free_instance->m_recursion_level ==
1634                m_recursion_level + 1));
1635   m_first_instance->m_first_free_instance= this;
1636 
1637   DBUG_RETURN(err_status);
1638 }
1639 
1640 
1641 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1642 /**
1643   set_routine_security_ctx() changes routine security context, and
1644   checks if there is an EXECUTE privilege in new context.  If there is
1645   no EXECUTE privilege, it changes the context back and returns a
1646   error.
1647 
1648   @param thd         thread handle
1649   @param sp          stored routine to change the context for
1650   @param save_ctx    pointer to an old security context
1651 
1652   @todo
1653     - Cache if the definer has the right to use the object on the
1654     first usage and only reset the cache if someone does a GRANT
1655     statement that 'may' affect this.
1656 
1657   @retval
1658     TRUE   if there was a error, and the context wasn't changed.
1659   @retval
1660     FALSE  if the context was changed.
1661 */
1662 
1663 bool
1664 set_routine_security_ctx(THD *thd, sp_head *sp, Security_context **save_ctx)
1665 {
1666   *save_ctx= 0;
1667   if (sp->suid() != SP_IS_NOT_SUID &&
1668       sp->m_security_ctx.change_security_context(thd, &sp->m_definer.user,
1669                                                  &sp->m_definer.host,
1670                                                  &sp->m_db,
1671                                                  save_ctx))
1672     return TRUE;
1673 
1674   /*
1675     If we changed context to run as another user, we need to check the
1676     access right for the new context again as someone may have revoked
1677     the right to use the procedure from this user.
1678 
1679     TODO:
1680       Cache if the definer has the right to use the object on the
1681       first usage and only reset the cache if someone does a GRANT
1682       statement that 'may' affect this.
1683   */
1684   if (*save_ctx &&
1685       sp->check_execute_access(thd))
1686   {
1687     sp->m_security_ctx.restore_security_context(thd, *save_ctx);
1688     *save_ctx= 0;
1689     return TRUE;
1690   }
1691 
1692   return FALSE;
1693 }
1694 #endif // ! NO_EMBEDDED_ACCESS_CHECKS
1695 
1696 
1697 bool sp_head::check_execute_access(THD *thd) const
1698 {
1699   return m_parent ? m_parent->check_execute_access(thd) :
1700                     check_routine_access(thd, EXECUTE_ACL,
1701                                          &m_db, &m_name,
1702                                          m_handler, false);
1703 }
1704 
1705 
1706 /**
1707   Create rcontext optionally using the routine security.
1708   This is important for sql_mode=ORACLE to make sure that the invoker has
1709   access to the tables mentioned in the %TYPE references.
1710 
1711   In non-Oracle sql_modes we do not need access to any tables,
1712   so we can omit the security context switch for performance purposes.
1713 
1714   @param thd
1715   @param ret_value
1716   @retval           NULL - error (access denided or EOM)
1717   @retval          !NULL - success (the invoker has rights to all %TYPE tables)
1718 */
1719 
1720 sp_rcontext *sp_head::rcontext_create(THD *thd, Field *ret_value,
1721                                       Row_definition_list *defs,
1722                                       bool switch_security_ctx)
1723 {
1724   if (!(m_flags & HAS_COLUMN_TYPE_REFS))
1725     return sp_rcontext::create(thd, this, m_pcont, ret_value, *defs);
1726   sp_rcontext *res= NULL;
1727 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1728   Security_context *save_security_ctx;
1729   if (switch_security_ctx &&
1730       set_routine_security_ctx(thd, this, &save_security_ctx))
1731     return NULL;
1732 #endif
1733   if (!defs->resolve_type_refs(thd))
1734     res= sp_rcontext::create(thd, this, m_pcont, ret_value, *defs);
1735 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1736   if (switch_security_ctx)
1737     m_security_ctx.restore_security_context(thd, save_security_ctx);
1738 #endif
1739   return res;
1740 }
1741 
1742 
1743 sp_rcontext *sp_head::rcontext_create(THD *thd, Field *ret_value,
1744                                       List<Item> *args)
1745 {
1746   DBUG_ASSERT(args);
1747   Row_definition_list defs;
1748   m_pcont->retrieve_field_definitions(&defs);
1749   if (defs.adjust_formal_params_to_actual_params(thd, args))
1750     return NULL;
1751   return rcontext_create(thd, ret_value, &defs, true);
1752 }
1753 
1754 
1755 sp_rcontext *sp_head::rcontext_create(THD *thd, Field *ret_value,
1756                                       Item **args, uint arg_count)
1757 {
1758   Row_definition_list defs;
1759   m_pcont->retrieve_field_definitions(&defs);
1760   if (defs.adjust_formal_params_to_actual_params(thd, args, arg_count))
1761     return NULL;
1762   return rcontext_create(thd, ret_value, &defs, true);
1763 }
1764 
1765 
1766 /**
1767   Execute trigger stored program.
1768 
1769   - changes security context for triggers
1770   - switch to new memroot
1771   - call sp_head::execute
1772   - restore old memroot
1773   - restores security context
1774 
1775   @param thd               Thread handle
1776   @param db                database name
1777   @param table             table name
1778   @param grant_info        GRANT_INFO structure to be filled with
1779                            information about definer's privileges
1780                            on subject table
1781 
1782   @todo
1783     - TODO: we should create sp_rcontext once per command and reuse it
1784     on subsequent executions of a trigger.
1785 
1786   @retval
1787     FALSE  on success
1788   @retval
1789     TRUE   on error
1790 */
1791 
1792 bool
1793 sp_head::execute_trigger(THD *thd,
1794                          const LEX_CSTRING *db_name,
1795                          const LEX_CSTRING *table_name,
1796                          GRANT_INFO *grant_info)
1797 {
1798   sp_rcontext *octx = thd->spcont;
1799   sp_rcontext *nctx = NULL;
1800   bool err_status= FALSE;
1801   MEM_ROOT call_mem_root;
1802   Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
1803   Query_arena backup_arena;
1804   DBUG_ENTER("sp_head::execute_trigger");
1805   DBUG_PRINT("info", ("trigger %s", m_name.str));
1806 
1807 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1808   Security_context *save_ctx= NULL;
1809 
1810 
1811   if (suid() != SP_IS_NOT_SUID &&
1812       m_security_ctx.change_security_context(thd,
1813                                              &m_definer.user,
1814                                              &m_definer.host,
1815                                              &m_db,
1816                                              &save_ctx))
1817     DBUG_RETURN(TRUE);
1818 
1819   /*
1820     Fetch information about table-level privileges for subject table into
1821     GRANT_INFO instance. The access check itself will happen in
1822     Item_trigger_field, where this information will be used along with
1823     information about column-level privileges.
1824   */
1825 
1826   fill_effective_table_privileges(thd,
1827                                   grant_info,
1828                                   db_name->str,
1829                                   table_name->str);
1830 
1831   /* Check that the definer has TRIGGER privilege on the subject table. */
1832 
1833   if (!(grant_info->privilege & TRIGGER_ACL))
1834   {
1835     char priv_desc[128];
1836     get_privilege_desc(priv_desc, sizeof(priv_desc), TRIGGER_ACL);
1837 
1838     my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), priv_desc,
1839              thd->security_ctx->priv_user, thd->security_ctx->host_or_ip,
1840              table_name->str);
1841 
1842     m_security_ctx.restore_security_context(thd, save_ctx);
1843     DBUG_RETURN(TRUE);
1844   }
1845 #endif // NO_EMBEDDED_ACCESS_CHECKS
1846 
1847   /*
1848     Prepare arena and memroot for objects which lifetime is whole
1849     duration of trigger call (sp_rcontext, it's tables and items,
1850     sp_cursor and Item_cache holders for case expressions).  We can't
1851     use caller's arena/memroot for those objects because in this case
1852     some fixed amount of memory will be consumed for each trigger
1853     invocation and so statements which involve lot of them will hog
1854     memory.
1855 
1856     TODO: we should create sp_rcontext once per command and reuse it
1857     on subsequent executions of a trigger.
1858   */
1859   init_sql_alloc(&call_mem_root, "execute_trigger", MEM_ROOT_BLOCK_SIZE, 0,
1860                  MYF(0));
1861   thd->set_n_backup_active_arena(&call_arena, &backup_arena);
1862 
1863   Row_definition_list defs;
1864   m_pcont->retrieve_field_definitions(&defs);
1865   if (!(nctx= rcontext_create(thd, NULL, &defs, false)))
1866   {
1867     err_status= TRUE;
1868     goto err_with_cleanup;
1869   }
1870 
1871   thd->spcont= nctx;
1872 
1873   err_status= execute(thd, FALSE);
1874 
1875 err_with_cleanup:
1876   thd->restore_active_arena(&call_arena, &backup_arena);
1877 
1878 #ifndef NO_EMBEDDED_ACCESS_CHECKS
1879   m_security_ctx.restore_security_context(thd, save_ctx);
1880 #endif // NO_EMBEDDED_ACCESS_CHECKS
1881 
1882   delete nctx;
1883   call_arena.free_items();
1884   free_root(&call_mem_root, MYF(0));
1885   thd->spcont= octx;
1886 
1887   if (thd->killed)
1888     thd->send_kill_message();
1889 
1890   DBUG_RETURN(err_status);
1891 }
1892 
1893 
1894 /*
1895   Execute the package initialization section.
1896 */
1897 
1898 bool sp_package::instantiate_if_needed(THD *thd)
1899 {
1900   List<Item> args;
1901   if (m_is_instantiated)
1902     return false;
1903   /*
1904     Set m_is_instantiated to true early, to avoid recursion in case if
1905     the package initialization section calls routines from the same package.
1906   */
1907   m_is_instantiated= true;
1908   /*
1909     Check that the initialization section doesn't contain Dynamic SQL
1910     and doesn't return result sets: such stored procedures can't
1911     be called from a function or trigger.
1912   */
1913   if (thd->in_sub_stmt)
1914   {
1915     const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ?
1916                         "trigger" : "function");
1917     if (is_not_allowed_in_function(where))
1918       goto err;
1919   }
1920 
1921   args.elements= 0;
1922   if (execute_procedure(thd, &args))
1923     goto err;
1924   return false;
1925 err:
1926   m_is_instantiated= false;
1927   return true;
1928 }
1929 
1930 
1931 /**
1932   Execute a function.
1933 
1934    - evaluate parameters
1935    - changes security context for SUID routines
1936    - switch to new memroot
1937    - call sp_head::execute
1938    - restore old memroot
1939    - evaluate the return value
1940    - restores security context
1941 
1942   @param thd               Thread handle
1943   @param argp              Passed arguments (these are items from containing
1944                            statement?)
1945   @param argcount          Number of passed arguments. We need to check if
1946                            this is correct.
1947   @param return_value_fld  Save result here.
1948 
1949   @todo
1950     We should create sp_rcontext once per command and reuse
1951     it on subsequent executions of a function/trigger.
1952 
1953   @todo
1954     In future we should associate call arena/mem_root with
1955     sp_rcontext and allocate all these objects (and sp_rcontext
1956     itself) on it directly rather than juggle with arenas.
1957 
1958   @retval
1959     FALSE  on success
1960   @retval
1961     TRUE   on error
1962 */
1963 
1964 bool
1965 sp_head::execute_function(THD *thd, Item **argp, uint argcount,
1966                           Field *return_value_fld, sp_rcontext **func_ctx,
1967                           Query_arena *call_arena)
1968 {
1969   ulonglong UNINIT_VAR(binlog_save_options);
1970   bool need_binlog_call= FALSE;
1971   uint arg_no;
1972   sp_rcontext *octx = thd->spcont;
1973   char buf[STRING_BUFFER_USUAL_SIZE];
1974   String binlog_buf(buf, sizeof(buf), &my_charset_bin);
1975   bool err_status= FALSE;
1976   Query_arena backup_arena;
1977   DBUG_ENTER("sp_head::execute_function");
1978   DBUG_PRINT("info", ("function %s", m_name.str));
1979 
1980   if (m_parent && m_parent->instantiate_if_needed(thd))
1981     DBUG_RETURN(true);
1982 
1983   /*
1984     Check that the function is called with all specified arguments.
1985 
1986     If it is not, use my_error() to report an error, or it will not terminate
1987     the invoking query properly.
1988   */
1989   if (argcount != m_pcont->context_var_count())
1990   {
1991     /*
1992       Need to use my_error here, or it will not terminate the
1993       invoking query properly.
1994     */
1995     my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0),
1996              "FUNCTION", ErrConvDQName(this).ptr(),
1997              m_pcont->context_var_count(), argcount);
1998     DBUG_RETURN(TRUE);
1999   }
2000   /*
2001     Prepare arena and memroot for objects which lifetime is whole
2002     duration of function call (sp_rcontext, it's tables and items,
2003     sp_cursor and Item_cache holders for case expressions).
2004     We can't use caller's arena/memroot for those objects because
2005     in this case some fixed amount of memory will be consumed for
2006     each function/trigger invocation and so statements which involve
2007     lot of them will hog memory.
2008     TODO: we should create sp_rcontext once per command and reuse
2009     it on subsequent executions of a function/trigger.
2010   */
2011   if (!(*func_ctx))
2012   {
2013     thd->set_n_backup_active_arena(call_arena, &backup_arena);
2014 
2015     if (!(*func_ctx= rcontext_create(thd, return_value_fld, argp, argcount)))
2016     {
2017       thd->restore_active_arena(call_arena, &backup_arena);
2018       err_status= TRUE;
2019       goto err_with_cleanup;
2020     }
2021 
2022     /*
2023       We have to switch temporarily back to callers arena/memroot.
2024       Function arguments belong to the caller and so the may reference
2025       memory which they will allocate during calculation long after
2026       this function call will be finished (e.g. in Item::cleanup()).
2027     */
2028     thd->restore_active_arena(call_arena, &backup_arena);
2029   }
2030 
2031   /* Pass arguments. */
2032   for (arg_no= 0; arg_no < argcount; arg_no++)
2033   {
2034     /* Arguments must be fixed in Item_func_sp::fix_fields */
2035     DBUG_ASSERT(argp[arg_no]->fixed);
2036 
2037     if ((err_status= (*func_ctx)->set_parameter(thd, arg_no, &(argp[arg_no]))))
2038       goto err_with_cleanup;
2039   }
2040 
2041   /*
2042     If row-based binlogging, we don't need to binlog the function's call, let
2043     each substatement be binlogged its way.
2044   */
2045   need_binlog_call= mysql_bin_log.is_open() &&
2046                     (thd->variables.option_bits & OPTION_BIN_LOG) &&
2047                     !thd->is_current_stmt_binlog_format_row();
2048 
2049   /*
2050     Remember the original arguments for unrolled replication of functions
2051     before they are changed by execution.
2052   */
2053   if (need_binlog_call)
2054   {
2055     binlog_buf.length(0);
2056     binlog_buf.append(STRING_WITH_LEN("SELECT "));
2057     append_identifier(thd, &binlog_buf, &m_db);
2058     binlog_buf.append('.');
2059     append_identifier(thd, &binlog_buf, &m_name);
2060     binlog_buf.append('(');
2061     for (arg_no= 0; arg_no < argcount; arg_no++)
2062     {
2063       String str_value_holder;
2064       String *str_value;
2065 
2066       if (arg_no)
2067         binlog_buf.append(',');
2068 
2069       Item_field *item= (*func_ctx)->get_parameter(arg_no);
2070       str_value= item->type_handler()->print_item_value(thd, item,
2071                                                         &str_value_holder);
2072       if (str_value)
2073         binlog_buf.append(*str_value);
2074       else
2075         binlog_buf.append(STRING_WITH_LEN("NULL"));
2076     }
2077     binlog_buf.append(')');
2078   }
2079   thd->spcont= *func_ctx;
2080 
2081 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2082   Security_context *save_security_ctx;
2083   if (set_routine_security_ctx(thd, this, &save_security_ctx))
2084   {
2085     err_status= TRUE;
2086     goto err_with_cleanup;
2087   }
2088 #endif
2089 
2090   if (need_binlog_call)
2091   {
2092     query_id_t q;
2093     reset_dynamic(&thd->user_var_events);
2094     /*
2095       In case of artificially constructed events for function calls
2096       we have separate union for each such event and hence can't use
2097       query_id of real calling statement as the start of all these
2098       unions (this will break logic of replication of user-defined
2099       variables). So we use artifical value which is guaranteed to
2100       be greater than all query_id's of all statements belonging
2101       to previous events/unions.
2102       Possible alternative to this is logging of all function invocations
2103       as one select and not resetting THD::user_var_events before
2104       each invocation.
2105     */
2106     q= get_query_id();
2107     mysql_bin_log.start_union_events(thd, q + 1);
2108     binlog_save_options= thd->variables.option_bits;
2109     thd->variables.option_bits&= ~OPTION_BIN_LOG;
2110   }
2111 
2112   /*
2113     Switch to call arena/mem_root so objects like sp_cursor or
2114     Item_cache holders for case expressions can be allocated on it.
2115 
2116     TODO: In future we should associate call arena/mem_root with
2117           sp_rcontext and allocate all these objects (and sp_rcontext
2118           itself) on it directly rather than juggle with arenas.
2119   */
2120   thd->set_n_backup_active_arena(call_arena, &backup_arena);
2121 
2122   err_status= execute(thd, TRUE);
2123 
2124   thd->restore_active_arena(call_arena, &backup_arena);
2125 
2126   if (need_binlog_call)
2127   {
2128     mysql_bin_log.stop_union_events(thd);
2129     thd->variables.option_bits= binlog_save_options;
2130     if (thd->binlog_evt_union.unioned_events)
2131     {
2132       int errcode = query_error_code(thd, thd->killed == NOT_KILLED);
2133       Query_log_event qinfo(thd, binlog_buf.ptr(), binlog_buf.length(),
2134                             thd->binlog_evt_union.unioned_events_trans, FALSE, FALSE, errcode);
2135       if (mysql_bin_log.write(&qinfo) &&
2136           thd->binlog_evt_union.unioned_events_trans)
2137       {
2138         push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR,
2139                      "Invoked ROUTINE modified a transactional table but MySQL "
2140                      "failed to reflect this change in the binary log");
2141         err_status= TRUE;
2142       }
2143       reset_dynamic(&thd->user_var_events);
2144       /* Forget those values, in case more function calls are binlogged: */
2145       thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0;
2146       thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty();
2147     }
2148   }
2149 
2150   if (!err_status && thd->spcont->quit_func)
2151   {
2152     /* We need result only in function but not in trigger */
2153 
2154     if (!(*func_ctx)->is_return_value_set())
2155     {
2156       my_error(ER_SP_NORETURNEND, MYF(0), m_name.str);
2157       err_status= TRUE;
2158     }
2159   }
2160 
2161 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2162   m_security_ctx.restore_security_context(thd, save_security_ctx);
2163 #endif
2164 
2165 err_with_cleanup:
2166   thd->spcont= octx;
2167 
2168   /*
2169     If not insided a procedure and a function printing warning
2170     messsages.
2171   */
2172   if (need_binlog_call &&
2173       thd->spcont == NULL && !thd->binlog_evt_union.do_union)
2174     thd->issue_unsafe_warnings();
2175 
2176   DBUG_RETURN(err_status);
2177 }
2178 
2179 
2180 /**
2181   Execute a procedure.
2182 
2183   The function does the following steps:
2184    - Set all parameters
2185    - changes security context for SUID routines
2186    - call sp_head::execute
2187    - copy back values of INOUT and OUT parameters
2188    - restores security context
2189 
2190   @param thd    Thread handle
2191   @param args   List of values passed as arguments.
2192 
2193   @retval
2194     FALSE  on success
2195   @retval
2196     TRUE   on error
2197 */
2198 
2199 bool
2200 sp_head::execute_procedure(THD *thd, List<Item> *args)
2201 {
2202   bool err_status= FALSE;
2203   uint params = m_pcont->context_var_count();
2204   /* Query start time may be reset in a multi-stmt SP; keep this for later. */
2205   ulonglong utime_before_sp_exec= thd->utime_after_lock;
2206   sp_rcontext *save_spcont, *octx;
2207   sp_rcontext *nctx = NULL;
2208   bool save_enable_slow_log;
2209   bool save_log_general= false;
2210   sp_package *pkg= get_package();
2211   DBUG_ENTER("sp_head::execute_procedure");
2212   DBUG_PRINT("info", ("procedure %s", m_name.str));
2213 
2214   if (m_parent && m_parent->instantiate_if_needed(thd))
2215     DBUG_RETURN(true);
2216 
2217   if (args->elements != params)
2218   {
2219     my_error(ER_SP_WRONG_NO_OF_ARGS, MYF(0), "PROCEDURE",
2220              ErrConvDQName(this).ptr(), params, args->elements);
2221     DBUG_RETURN(TRUE);
2222   }
2223 
2224   save_spcont= octx= thd->spcont;
2225   if (! octx)
2226   {
2227     /* Create a temporary old context. */
2228     if (!(octx= rcontext_create(thd, NULL, args)))
2229     {
2230       DBUG_PRINT("error", ("Could not create octx"));
2231       DBUG_RETURN(TRUE);
2232     }
2233 
2234     thd->spcont= octx;
2235 
2236     /* set callers_arena to thd, for upper-level function to work */
2237     thd->spcont->callers_arena= thd;
2238   }
2239 
2240   if (!pkg)
2241   {
2242     if (!(nctx= rcontext_create(thd, NULL, args)))
2243     {
2244       delete nctx; /* Delete nctx if it was init() that failed. */
2245       thd->spcont= save_spcont;
2246       DBUG_RETURN(TRUE);
2247     }
2248   }
2249   else
2250   {
2251     if (!pkg->m_rcontext)
2252     {
2253       Query_arena backup_arena;
2254       thd->set_n_backup_active_arena(this, &backup_arena);
2255       nctx= pkg->rcontext_create(thd, NULL, args);
2256       thd->restore_active_arena(this, &backup_arena);
2257       if (!nctx)
2258       {
2259         thd->spcont= save_spcont;
2260         DBUG_RETURN(TRUE);
2261       }
2262       pkg->m_rcontext= nctx;
2263     }
2264     else
2265       nctx= pkg->m_rcontext;
2266   }
2267 
2268   if (params > 0)
2269   {
2270     List_iterator<Item> it_args(*args);
2271 
2272     DBUG_PRINT("info",(" %.*s: eval args", (int) m_name.length, m_name.str));
2273 
2274     for (uint i= 0 ; i < params ; i++)
2275     {
2276       Item *arg_item= it_args++;
2277 
2278       if (!arg_item)
2279         break;
2280 
2281       sp_variable *spvar= m_pcont->find_variable(i);
2282 
2283       if (!spvar)
2284         continue;
2285 
2286       if (spvar->mode != sp_variable::MODE_IN)
2287       {
2288         Settable_routine_parameter *srp=
2289           arg_item->get_settable_routine_parameter();
2290 
2291         if (!srp)
2292         {
2293           my_error(ER_SP_NOT_VAR_ARG, MYF(0), i+1, ErrConvDQName(this).ptr());
2294           err_status= TRUE;
2295           break;
2296         }
2297 
2298         srp->set_required_privilege(spvar->mode == sp_variable::MODE_INOUT);
2299       }
2300 
2301       if (spvar->mode == sp_variable::MODE_OUT)
2302       {
2303         Item_null *null_item= new (thd->mem_root) Item_null(thd);
2304         Item *tmp_item= null_item;
2305 
2306         if (!null_item ||
2307             nctx->set_parameter(thd, i, &tmp_item))
2308         {
2309           DBUG_PRINT("error", ("set variable failed"));
2310           err_status= TRUE;
2311           break;
2312         }
2313       }
2314       else
2315       {
2316         if (nctx->set_parameter(thd, i, it_args.ref()))
2317         {
2318           DBUG_PRINT("error", ("set variable 2 failed"));
2319           err_status= TRUE;
2320           break;
2321         }
2322       }
2323 
2324       TRANSACT_TRACKER(add_trx_state_from_thd(thd));
2325     }
2326 
2327     /*
2328       Okay, got values for all arguments. Close tables that might be used by
2329       arguments evaluation. If arguments evaluation required prelocking mode,
2330       we'll leave it here.
2331     */
2332     thd->lex->unit.cleanup();
2333 
2334     if (!thd->in_sub_stmt)
2335     {
2336       thd->get_stmt_da()->set_overwrite_status(true);
2337       thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
2338       thd->get_stmt_da()->set_overwrite_status(false);
2339     }
2340 
2341     close_thread_tables(thd);
2342     thd_proc_info(thd, 0);
2343 
2344     if (! thd->in_sub_stmt)
2345     {
2346       if (thd->transaction_rollback_request)
2347       {
2348         trans_rollback_implicit(thd);
2349         thd->release_transactional_locks();
2350       }
2351       else if (! thd->in_multi_stmt_transaction_mode())
2352         thd->release_transactional_locks();
2353       else
2354         thd->mdl_context.release_statement_locks();
2355     }
2356 
2357     thd->rollback_item_tree_changes();
2358 
2359     DBUG_PRINT("info",(" %.*s: eval args done", (int) m_name.length,
2360                        m_name.str));
2361   }
2362 
2363   save_enable_slow_log= thd->enable_slow_log;
2364 
2365   /*
2366     Disable slow log if:
2367     - Slow logging is enabled (no change needed)
2368     - This is a normal SP (not event log)
2369     - If we have not explicitely disabled logging of SP
2370   */
2371   if (save_enable_slow_log &&
2372       ((!(m_flags & LOG_SLOW_STATEMENTS) &&
2373         (thd->variables.log_slow_disabled_statements & LOG_SLOW_DISABLE_SP))))
2374   {
2375     DBUG_PRINT("info", ("Disabling slow log for the execution"));
2376     thd->enable_slow_log= FALSE;
2377   }
2378 
2379   /*
2380     Disable general log if:
2381     - If general log is enabled (no change needed)
2382     - This is a normal SP (not event log)
2383     - If we have not explicitely disabled logging of SP
2384   */
2385   if (!(thd->variables.option_bits & OPTION_LOG_OFF) &&
2386       (!(m_flags & LOG_GENERAL_LOG) &&
2387        (thd->variables.log_disabled_statements & LOG_DISABLE_SP)))
2388   {
2389     DBUG_PRINT("info", ("Disabling general log for the execution"));
2390     save_log_general= true;
2391     /* disable this bit */
2392     thd->variables.option_bits |= OPTION_LOG_OFF;
2393   }
2394   thd->spcont= nctx;
2395 
2396 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2397   Security_context *save_security_ctx= 0;
2398   if (!err_status)
2399     err_status= set_routine_security_ctx(thd, this, &save_security_ctx);
2400 #endif
2401 
2402   if (!err_status)
2403   {
2404     err_status= execute(thd, TRUE);
2405   }
2406 
2407   if (save_log_general)
2408     thd->variables.option_bits &= ~OPTION_LOG_OFF;
2409   thd->enable_slow_log= save_enable_slow_log;
2410 
2411   /*
2412     In the case when we weren't able to employ reuse mechanism for
2413     OUT/INOUT paranmeters, we should reallocate memory. This
2414     allocation should be done on the arena which will live through
2415     all execution of calling routine.
2416   */
2417   thd->spcont->callers_arena= octx->callers_arena;
2418 
2419   if (!err_status && params > 0)
2420   {
2421     List_iterator<Item> it_args(*args);
2422 
2423     /*
2424       Copy back all OUT or INOUT values to the previous frame, or
2425       set global user variables
2426     */
2427     for (uint i= 0 ; i < params ; i++)
2428     {
2429       Item *arg_item= it_args++;
2430 
2431       if (!arg_item)
2432         break;
2433 
2434       sp_variable *spvar= m_pcont->find_variable(i);
2435 
2436       if (spvar->mode == sp_variable::MODE_IN)
2437         continue;
2438 
2439       Settable_routine_parameter *srp=
2440         arg_item->get_settable_routine_parameter();
2441 
2442       DBUG_ASSERT(srp);
2443 
2444       if (srp->set_value(thd, octx, nctx->get_variable_addr(i)))
2445       {
2446         DBUG_PRINT("error", ("set value failed"));
2447         err_status= TRUE;
2448         break;
2449       }
2450 
2451       Send_field *out_param_info= new (thd->mem_root) Send_field();
2452       nctx->get_parameter(i)->make_send_field(thd, out_param_info);
2453       out_param_info->db_name= m_db.str;
2454       out_param_info->table_name= m_name.str;
2455       out_param_info->org_table_name= m_name.str;
2456       out_param_info->col_name= spvar->name;
2457       out_param_info->org_col_name= spvar->name;
2458 
2459       srp->set_out_param_info(out_param_info);
2460     }
2461   }
2462 
2463 #ifndef NO_EMBEDDED_ACCESS_CHECKS
2464   if (save_security_ctx)
2465     m_security_ctx.restore_security_context(thd, save_security_ctx);
2466 #endif
2467 
2468   if (!save_spcont)
2469     delete octx;
2470 
2471   if (!pkg)
2472     delete nctx;
2473   thd->spcont= save_spcont;
2474   thd->utime_after_lock= utime_before_sp_exec;
2475 
2476   /*
2477     If not insided a procedure and a function printing warning
2478     messsages.
2479   */
2480   bool need_binlog_call= mysql_bin_log.is_open() &&
2481                          (thd->variables.option_bits & OPTION_BIN_LOG) &&
2482                          !thd->is_current_stmt_binlog_format_row();
2483   if (need_binlog_call && thd->spcont == NULL &&
2484       !thd->binlog_evt_union.do_union)
2485     thd->issue_unsafe_warnings();
2486 
2487   DBUG_RETURN(err_status);
2488 }
2489 
2490 
2491 /**
2492   Reset lex during parsing, before we parse a sub statement.
2493 
2494   @param thd Thread handler.
2495 
2496   @return Error state
2497     @retval true An error occurred.
2498     @retval false Success.
2499 */
2500 
2501 bool
2502 sp_head::reset_lex(THD *thd, sp_lex_local *sublex)
2503 {
2504   DBUG_ENTER("sp_head::reset_lex");
2505   LEX *oldlex= thd->lex;
2506 
2507   thd->set_local_lex(sublex);
2508 
2509   DBUG_RETURN(m_lex.push_front(oldlex));
2510 }
2511 
2512 
2513 bool
2514 sp_head::reset_lex(THD *thd)
2515 {
2516   DBUG_ENTER("sp_head::reset_lex");
2517   sp_lex_local *sublex= new (thd->mem_root) sp_lex_local(thd, thd->lex);
2518   DBUG_RETURN(sublex ? reset_lex(thd, sublex) : true);
2519 }
2520 
2521 
2522 /**
2523   Restore lex during parsing, after we have parsed a sub statement.
2524 
2525   @param thd Thread handle
2526   @param oldlex The upper level lex we're near to restore to
2527   @param sublex The local lex we're near to restore from
2528 
2529   @return
2530     @retval TRUE failure
2531     @retval FALSE success
2532 */
2533 
2534 bool
2535 sp_head::merge_lex(THD *thd, LEX *oldlex, LEX *sublex)
2536 {
2537   DBUG_ENTER("sp_head::merge_lex");
2538 
2539   sublex->set_trg_event_type_for_tables();
2540 
2541   oldlex->trg_table_fields.push_back(&sublex->trg_table_fields);
2542 
2543   /* If this substatement is unsafe, the entire routine is too. */
2544   DBUG_PRINT("info", ("sublex->get_stmt_unsafe_flags: 0x%x",
2545                       sublex->get_stmt_unsafe_flags()));
2546   unsafe_flags|= sublex->get_stmt_unsafe_flags();
2547 
2548   /*
2549     Add routines which are used by statement to respective set for
2550     this routine.
2551   */
2552   if (sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines))
2553     DBUG_RETURN(TRUE);
2554 
2555   /* If this substatement is a update query, then mark MODIFIES_DATA */
2556   if (is_update_query(sublex->sql_command))
2557     m_flags|= MODIFIES_DATA;
2558 
2559   /*
2560     Merge tables used by this statement (but not by its functions or
2561     procedures) to multiset of tables used by this routine.
2562   */
2563   merge_table_list(thd, sublex->query_tables, sublex);
2564   /* Merge lists of PS parameters. */
2565   oldlex->param_list.append(&sublex->param_list);
2566 
2567   DBUG_RETURN(FALSE);
2568 }
2569 
2570 /**
2571   Put the instruction on the backpatch list, associated with the label.
2572 */
2573 
2574 int
2575 sp_head::push_backpatch(THD *thd, sp_instr *i, sp_label *lab,
2576                         List<bp_t> *list, backpatch_instr_type itype)
2577 {
2578   bp_t *bp= (bp_t *) thd->alloc(sizeof(bp_t));
2579 
2580   if (!bp)
2581     return 1;
2582   bp->lab= lab;
2583   bp->instr= i;
2584   bp->instr_type= itype;
2585   return list->push_front(bp);
2586 }
2587 
2588 int
2589 sp_head::push_backpatch(THD *thd, sp_instr *i, sp_label *lab)
2590 {
2591   return push_backpatch(thd, i, lab, &m_backpatch, GOTO);
2592 }
2593 
2594 int
2595 sp_head::push_backpatch_goto(THD *thd, sp_pcontext *ctx, sp_label *lab)
2596 {
2597   uint ip= instructions();
2598 
2599   /*
2600     Add cpop/hpop : they will be removed or updated later if target is in
2601     the same block or not
2602   */
2603   sp_instr_hpop *hpop= new (thd->mem_root) sp_instr_hpop(ip++, ctx, 0);
2604   if (hpop == NULL || add_instr(hpop))
2605     return true;
2606   if (push_backpatch(thd, hpop, lab, &m_backpatch_goto, HPOP))
2607     return true;
2608 
2609   sp_instr_cpop *cpop= new (thd->mem_root) sp_instr_cpop(ip++, ctx, 0);
2610   if (cpop == NULL || add_instr(cpop))
2611     return true;
2612   if (push_backpatch(thd, cpop, lab, &m_backpatch_goto, CPOP))
2613     return true;
2614 
2615   // Add jump with ip=0. IP will be updated when label is found.
2616   sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(ip, ctx);
2617   if (i == NULL || add_instr(i))
2618     return true;
2619   if (push_backpatch(thd, i, lab, &m_backpatch_goto, GOTO))
2620     return true;
2621 
2622   return false;
2623 }
2624 
2625 /**
2626   Update all instruction with this label in the backpatch list to
2627   the current position.
2628 */
2629 
2630 void
2631 sp_head::backpatch(sp_label *lab)
2632 {
2633   bp_t *bp;
2634   uint dest= instructions();
2635   List_iterator_fast<bp_t> li(m_backpatch);
2636 
2637   DBUG_ENTER("sp_head::backpatch");
2638   while ((bp= li++))
2639   {
2640     if (bp->lab == lab)
2641     {
2642       DBUG_PRINT("info", ("backpatch: (m_ip %d, label %p <%s>) to dest %d",
2643                           bp->instr->m_ip, lab, lab->name.str, dest));
2644       bp->instr->backpatch(dest, lab->ctx);
2645     }
2646   }
2647   DBUG_VOID_RETURN;
2648 }
2649 
2650 void
2651 sp_head::backpatch_goto(THD *thd, sp_label *lab,sp_label *lab_begin_block)
2652 {
2653   bp_t *bp;
2654   uint dest= instructions();
2655   List_iterator<bp_t> li(m_backpatch_goto);
2656 
2657   DBUG_ENTER("sp_head::backpatch_goto");
2658   while ((bp= li++))
2659   {
2660     if (bp->instr->m_ip < lab_begin_block->ip || bp->instr->m_ip > lab->ip)
2661     {
2662       /*
2663         Update only jump target from the beginning of the block where the
2664         label is defined.
2665       */
2666       continue;
2667     }
2668     if (lex_string_cmp(system_charset_info, &bp->lab->name, &lab->name) == 0)
2669     {
2670       if (bp->instr_type == GOTO)
2671       {
2672         DBUG_PRINT("info",
2673                    ("backpatch_goto: (m_ip %d, label %p <%s>) to dest %d",
2674                     bp->instr->m_ip, lab, lab->name.str, dest));
2675         bp->instr->backpatch(dest, lab->ctx);
2676         // Jump resolved, remove from the list
2677         li.remove();
2678         continue;
2679       }
2680       if (bp->instr_type == CPOP)
2681       {
2682         uint n= bp->instr->m_ctx->diff_cursors(lab_begin_block->ctx, true);
2683         if (n == 0)
2684         {
2685           // Remove cpop instr
2686           replace_instr_to_nop(thd,bp->instr->m_ip);
2687         }
2688         else
2689         {
2690           // update count of cpop
2691           static_cast<sp_instr_cpop*>(bp->instr)->update_count(n);
2692           n= 1;
2693         }
2694         li.remove();
2695         continue;
2696       }
2697       if (bp->instr_type == HPOP)
2698       {
2699         uint n= bp->instr->m_ctx->diff_handlers(lab_begin_block->ctx, true);
2700         if (n == 0)
2701         {
2702           // Remove hpop instr
2703           replace_instr_to_nop(thd,bp->instr->m_ip);
2704         }
2705         else
2706         {
2707           // update count of cpop
2708           static_cast<sp_instr_hpop*>(bp->instr)->update_count(n);
2709           n= 1;
2710         }
2711         li.remove();
2712         continue;
2713       }
2714     }
2715   }
2716   DBUG_VOID_RETURN;
2717 }
2718 
2719 bool
2720 sp_head::check_unresolved_goto()
2721 {
2722   DBUG_ENTER("sp_head::check_unresolved_goto");
2723   bool has_unresolved_label=false;
2724   if (m_backpatch_goto.elements > 0)
2725   {
2726     List_iterator_fast<bp_t> li(m_backpatch_goto);
2727     while (bp_t* bp= li++)
2728     {
2729       if (bp->instr_type == GOTO)
2730       {
2731         my_error(ER_SP_LILABEL_MISMATCH, MYF(0), "GOTO", bp->lab->name.str);
2732         has_unresolved_label=true;
2733       }
2734     }
2735   }
2736   DBUG_RETURN(has_unresolved_label);
2737 }
2738 
2739 int
2740 sp_head::new_cont_backpatch(sp_instr_opt_meta *i)
2741 {
2742   m_cont_level+= 1;
2743   if (i)
2744   {
2745     /* Use the cont. destination slot to store the level */
2746     i->m_cont_dest= m_cont_level;
2747     if (m_cont_backpatch.push_front(i))
2748       return 1;
2749   }
2750   return 0;
2751 }
2752 
2753 int
2754 sp_head::add_cont_backpatch(sp_instr_opt_meta *i)
2755 {
2756   i->m_cont_dest= m_cont_level;
2757   return m_cont_backpatch.push_front(i);
2758 }
2759 
2760 void
2761 sp_head::do_cont_backpatch()
2762 {
2763   uint dest= instructions();
2764   uint lev= m_cont_level--;
2765   sp_instr_opt_meta *i;
2766 
2767   while ((i= m_cont_backpatch.head()) && i->m_cont_dest == lev)
2768   {
2769     i->m_cont_dest= dest;
2770     (void)m_cont_backpatch.pop();
2771   }
2772 }
2773 
2774 
2775 bool
2776 sp_head::sp_add_instr_cpush_for_cursors(THD *thd, sp_pcontext *pcontext)
2777 {
2778   for (uint i= 0; i < pcontext->frame_cursor_count(); i++)
2779   {
2780     const sp_pcursor *c= pcontext->get_cursor_by_local_frame_offset(i);
2781     sp_instr_cpush *instr= new (thd->mem_root)
2782                              sp_instr_cpush(instructions(), pcontext, c->lex(),
2783                                             pcontext->cursor_offset() + i);
2784     if (instr == NULL || add_instr(instr))
2785       return true;
2786   }
2787   return false;
2788 }
2789 
2790 
2791 void
2792 sp_head::set_chistics(const st_sp_chistics &chistics)
2793 {
2794   m_chistics.set(chistics);
2795   if (m_chistics.comment.length == 0)
2796     m_chistics.comment.str= 0;
2797   else
2798     m_chistics.comment.str= strmake_root(mem_root,
2799                                          m_chistics.comment.str,
2800                                          m_chistics.comment.length);
2801 }
2802 
2803 void
2804 sp_head::set_info(longlong created, longlong modified,
2805                   const st_sp_chistics &chistics, sql_mode_t sql_mode)
2806 {
2807   m_created= created;
2808   m_modified= modified;
2809   set_chistics(chistics);
2810   m_sql_mode= sql_mode;
2811 }
2812 
2813 
2814 void
2815 sp_head::reset_thd_mem_root(THD *thd)
2816 {
2817   DBUG_ENTER("sp_head::reset_thd_mem_root");
2818   m_thd_root= thd->mem_root;
2819   thd->mem_root= &main_mem_root;
2820   DBUG_PRINT("info", ("mem_root %p moved to thd mem root %p",
2821                       &mem_root, &thd->mem_root));
2822   free_list= thd->free_list; // Keep the old list
2823   thd->free_list= NULL; // Start a new one
2824   m_thd= thd;
2825   DBUG_VOID_RETURN;
2826 }
2827 
2828 void
2829 sp_head::restore_thd_mem_root(THD *thd)
2830 {
2831   DBUG_ENTER("sp_head::restore_thd_mem_root");
2832 
2833   /*
2834    In some cases our parser detects a syntax error and calls
2835    LEX::cleanup_lex_after_parse_error() method only after
2836    finishing parsing the whole routine. In such a situation
2837    sp_head::restore_thd_mem_root() will be called twice - the
2838    first time as part of normal parsing process and the second
2839    time by cleanup_lex_after_parse_error().
2840    To avoid ruining active arena/mem_root state in this case we
2841    skip restoration of old arena/mem_root if this method has been
2842    already called for this routine.
2843   */
2844   if (!m_thd)
2845     DBUG_VOID_RETURN;
2846 
2847   Item *flist= free_list;	// The old list
2848   set_query_arena(thd);         // Get new free_list and mem_root
2849   state= STMT_INITIALIZED_FOR_SP;
2850 
2851   DBUG_PRINT("info", ("mem_root %p returned from thd mem root %p",
2852                       &mem_root, &thd->mem_root));
2853   thd->free_list= flist;        // Restore the old one
2854   thd->mem_root= m_thd_root;
2855   m_thd= NULL;
2856   DBUG_VOID_RETURN;
2857 }
2858 
2859 
2860 /**
2861   Check if a user has access right to a routine.
2862 
2863   @param thd          Thread handler
2864   @param sp           SP
2865   @param full_access  Set to 1 if the user has SELECT right to the
2866                       'mysql.proc' able or is the owner of the routine
2867   @retval
2868     false ok
2869   @retval
2870     true  error
2871 */
2872 
2873 bool check_show_routine_access(THD *thd, sp_head *sp, bool *full_access)
2874 {
2875   TABLE_LIST tables;
2876   bzero((char*) &tables,sizeof(tables));
2877   tables.db= MYSQL_SCHEMA_NAME;
2878   tables.table_name= MYSQL_PROC_NAME;
2879   tables.alias= MYSQL_PROC_NAME;
2880 
2881   *full_access= ((!check_table_access(thd, SELECT_ACL, &tables, FALSE,
2882                                      1, TRUE) &&
2883                   (tables.grant.privilege & SELECT_ACL) != 0) ||
2884                  /* Check if user owns the routine. */
2885                  (!strcmp(sp->m_definer.user.str,
2886                           thd->security_ctx->priv_user) &&
2887                   !strcmp(sp->m_definer.host.str,
2888                           thd->security_ctx->priv_host)) ||
2889                  /* Check if current role or any of the sub-granted roles
2890                     own the routine. */
2891                  (sp->m_definer.host.length == 0 &&
2892                   (!strcmp(sp->m_definer.user.str,
2893                            thd->security_ctx->priv_role) ||
2894                    check_role_is_granted(thd->security_ctx->priv_role, NULL,
2895                                          sp->m_definer.user.str))));
2896   if (!*full_access)
2897     return check_some_routine_access(thd, sp->m_db.str, sp->m_name.str,
2898                                      sp->m_handler);
2899   return 0;
2900 }
2901 
2902 
2903 /**
2904   Collect metadata for SHOW CREATE statement for stored routines.
2905 
2906   @param thd  Thread context.
2907   @param sph          Stored routine handler
2908   @param fields       Item list to populate
2909 
2910   @return Error status.
2911     @retval FALSE on success
2912     @retval TRUE on error
2913 */
2914 
2915 void
2916 sp_head::show_create_routine_get_fields(THD *thd, const Sp_handler *sph,
2917                                                   List<Item> *fields)
2918 {
2919   const char *col1_caption= sph->show_create_routine_col1_caption();
2920   const char *col3_caption= sph->show_create_routine_col3_caption();
2921 
2922   MEM_ROOT *mem_root= thd->mem_root;
2923 
2924   /* Send header. */
2925 
2926   fields->push_back(new (mem_root)
2927                     Item_empty_string(thd, col1_caption, NAME_CHAR_LEN),
2928                     mem_root);
2929   fields->push_back(new (mem_root)
2930                     Item_empty_string(thd, "sql_mode", 256),
2931                     mem_root);
2932 
2933   {
2934     /*
2935       NOTE: SQL statement field must be not less than 1024 in order not to
2936       confuse old clients.
2937     */
2938 
2939     Item_empty_string *stmt_fld=
2940       new (mem_root) Item_empty_string(thd, col3_caption, 1024);
2941     stmt_fld->maybe_null= TRUE;
2942 
2943     fields->push_back(stmt_fld, mem_root);
2944   }
2945 
2946   fields->push_back(new (mem_root)
2947                    Item_empty_string(thd, "character_set_client",
2948                                      MY_CS_NAME_SIZE),
2949                    mem_root);
2950 
2951   fields->push_back(new (mem_root)
2952                    Item_empty_string(thd, "collation_connection",
2953                                      MY_CS_NAME_SIZE),
2954                    mem_root);
2955 
2956   fields->push_back(new (mem_root)
2957                    Item_empty_string(thd, "Database Collation",
2958                                      MY_CS_NAME_SIZE),
2959                    mem_root);
2960 }
2961 
2962 
2963 /**
2964   Implement SHOW CREATE statement for stored routines.
2965 
2966   @param thd  Thread context.
2967   @param sph  Stored routine handler
2968 
2969   @return Error status.
2970     @retval FALSE on success
2971     @retval TRUE on error
2972 */
2973 
2974 bool
2975 sp_head::show_create_routine(THD *thd, const Sp_handler *sph)
2976 {
2977   const char *col1_caption= sph->show_create_routine_col1_caption();
2978   const char *col3_caption= sph->show_create_routine_col3_caption();
2979 
2980   bool err_status;
2981 
2982   Protocol *protocol= thd->protocol;
2983   List<Item> fields;
2984 
2985   LEX_CSTRING sql_mode;
2986 
2987   bool full_access;
2988   MEM_ROOT *mem_root= thd->mem_root;
2989 
2990   DBUG_ENTER("sp_head::show_create_routine");
2991   DBUG_PRINT("info", ("routine %s", m_name.str));
2992 
2993   if (check_show_routine_access(thd, this, &full_access))
2994     DBUG_RETURN(TRUE);
2995 
2996   sql_mode_string_representation(thd, m_sql_mode, &sql_mode);
2997 
2998   /* Send header. */
2999 
3000   fields.push_back(new (mem_root)
3001                    Item_empty_string(thd, col1_caption, NAME_CHAR_LEN),
3002                    thd->mem_root);
3003   fields.push_back(new (mem_root)
3004                    Item_empty_string(thd, "sql_mode", (uint)sql_mode.length),
3005                    thd->mem_root);
3006 
3007   {
3008     /*
3009       NOTE: SQL statement field must be not less than 1024 in order not to
3010       confuse old clients.
3011     */
3012 
3013     Item_empty_string *stmt_fld=
3014       new (mem_root) Item_empty_string(thd, col3_caption,
3015                             (uint)MY_MAX(m_defstr.length, 1024));
3016 
3017     stmt_fld->maybe_null= TRUE;
3018 
3019     fields.push_back(stmt_fld, thd->mem_root);
3020   }
3021 
3022   fields.push_back(new (mem_root)
3023                    Item_empty_string(thd, "character_set_client",
3024                                      MY_CS_NAME_SIZE),
3025                    thd->mem_root);
3026 
3027   fields.push_back(new (mem_root)
3028                    Item_empty_string(thd, "collation_connection",
3029                                      MY_CS_NAME_SIZE),
3030                    thd->mem_root);
3031 
3032   fields.push_back(new (mem_root)
3033                    Item_empty_string(thd, "Database Collation",
3034                                      MY_CS_NAME_SIZE),
3035                    thd->mem_root);
3036 
3037   if (protocol->send_result_set_metadata(&fields,
3038                             Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
3039   {
3040     DBUG_RETURN(TRUE);
3041   }
3042 
3043   /* Send data. */
3044 
3045   protocol->prepare_for_resend();
3046 
3047   protocol->store(m_name.str, m_name.length, system_charset_info);
3048   protocol->store(sql_mode.str, sql_mode.length, system_charset_info);
3049 
3050   if (full_access)
3051     protocol->store(m_defstr.str, m_defstr.length,
3052                     m_creation_ctx->get_client_cs());
3053   else
3054     protocol->store_null();
3055 
3056 
3057   protocol->store(m_creation_ctx->get_client_cs()->csname, system_charset_info);
3058   protocol->store(m_creation_ctx->get_connection_cl()->name, system_charset_info);
3059   protocol->store(m_creation_ctx->get_db_cl()->name, system_charset_info);
3060 
3061   err_status= protocol->write();
3062 
3063   if (!err_status)
3064     my_eof(thd);
3065 
3066   DBUG_RETURN(err_status);
3067 }
3068 
3069 
3070 /**
3071   Add instruction to SP.
3072 
3073   @param instr   Instruction
3074 */
3075 
3076 int sp_head::add_instr(sp_instr *instr)
3077 {
3078   instr->free_list= m_thd->free_list;
3079   m_thd->free_list= 0;
3080   /*
3081     Memory root of every instruction is designated for permanent
3082     transformations (optimizations) made on the parsed tree during
3083     the first execution. It points to the memory root of the
3084     entire stored procedure, as their life span is equal.
3085   */
3086   instr->mem_root= &main_mem_root;
3087   instr->m_lineno= m_thd->m_parser_state->m_lip.yylineno;
3088   return insert_dynamic(&m_instr, (uchar*)&instr);
3089 }
3090 
3091 
3092 bool sp_head::add_instr_jump(THD *thd, sp_pcontext *spcont)
3093 {
3094   sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(instructions(), spcont);
3095   return i == NULL || add_instr(i);
3096 }
3097 
3098 
3099 bool sp_head::add_instr_jump(THD *thd, sp_pcontext *spcont, uint dest)
3100 {
3101   sp_instr_jump *i= new (thd->mem_root) sp_instr_jump(instructions(),
3102                                                       spcont, dest);
3103   return i == NULL || add_instr(i);
3104 }
3105 
3106 
3107 bool sp_head::add_instr_jump_forward_with_backpatch(THD *thd,
3108                                                     sp_pcontext *spcont,
3109                                                     sp_label *lab)
3110 {
3111   sp_instr_jump  *i= new (thd->mem_root) sp_instr_jump(instructions(), spcont);
3112   if (i == NULL || add_instr(i))
3113     return true;
3114   push_backpatch(thd, i, lab);
3115   return false;
3116 }
3117 
3118 
3119 bool sp_head::add_instr_freturn(THD *thd, sp_pcontext *spcont,
3120                                 Item *item, LEX *lex)
3121 {
3122   sp_instr_freturn *i= new (thd->mem_root)
3123                        sp_instr_freturn(instructions(), spcont, item,
3124                        m_return_field_def.type_handler(), thd->lex);
3125   if (i == NULL || add_instr(i))
3126     return true;
3127   m_flags|= sp_head::HAS_RETURN;
3128   return false;
3129 }
3130 
3131 
3132 bool sp_head::add_instr_preturn(THD *thd, sp_pcontext *spcont)
3133 {
3134   sp_instr_preturn *i= new (thd->mem_root)
3135                        sp_instr_preturn(instructions(), spcont);
3136   if (i == NULL || add_instr(i))
3137     return true;
3138   return false;
3139 }
3140 
3141 
3142 /*
3143   Replace an instruction at position to "no operation".
3144 
3145   @param thd - use mem_root of this THD for "new".
3146   @param ip  - position of the operation
3147   @returns   - true on error, false on success
3148 
3149   When we need to remove an instruction that during compilation
3150   appeared to be useless (typically as useless jump), we replace
3151   it to a jump to exactly the next instruction.
3152   Such jumps are later removed during sp_head::optimize().
3153 
3154   QQ: Perhaps we need a dedicated sp_instr_nop for this purpose.
3155 */
3156 
3157 bool sp_head::replace_instr_to_nop(THD *thd, uint ip)
3158 {
3159   sp_instr *instr= get_instr(ip);
3160   sp_instr_jump *nop= new (thd->mem_root) sp_instr_jump(instr->m_ip,
3161                                                         instr->m_ctx,
3162                                                         instr->m_ip + 1);
3163   if (!nop)
3164     return true;
3165   delete instr;
3166   set_dynamic(&m_instr, (uchar *) &nop, ip);
3167   return false;
3168 }
3169 
3170 
3171 /**
3172   Do some minimal optimization of the code:
3173     -# Mark used instructions
3174     -# While doing this, shortcut jumps to jump instructions
3175     -# Compact the code, removing unused instructions.
3176 
3177   This is the main mark and move loop; it relies on the following methods
3178   in sp_instr and its subclasses:
3179 
3180     - opt_mark()         :  Mark instruction as reachable
3181     - opt_shortcut_jump():  Shortcut jumps to the final destination;
3182                            used by opt_mark().
3183     - opt_move()         :  Update moved instruction
3184     - set_destination()  :  Set the new destination (jump instructions only)
3185 */
3186 
3187 void sp_head::optimize()
3188 {
3189   List<sp_instr> bp;
3190   sp_instr *i;
3191   uint src, dst;
3192 
3193   DBUG_EXECUTE_IF("sp_head_optimize_disable", return; );
3194 
3195   opt_mark();
3196 
3197   bp.empty();
3198   src= dst= 0;
3199   while ((i= get_instr(src)))
3200   {
3201     if (! i->marked)
3202     {
3203       delete i;
3204       src+= 1;
3205     }
3206     else
3207     {
3208       if (src != dst)
3209       {
3210         /* Move the instruction and update prev. jumps */
3211         sp_instr *ibp;
3212         List_iterator_fast<sp_instr> li(bp);
3213 
3214         set_dynamic(&m_instr, (uchar*)&i, dst);
3215         while ((ibp= li++))
3216         {
3217           sp_instr_opt_meta *im= static_cast<sp_instr_opt_meta *>(ibp);
3218           im->set_destination(src, dst);
3219         }
3220       }
3221       i->opt_move(dst, &bp);
3222       src+= 1;
3223       dst+= 1;
3224     }
3225   }
3226   m_instr.elements= dst;
3227   bp.empty();
3228 }
3229 
3230 void sp_head::add_mark_lead(uint ip, List<sp_instr> *leads)
3231 {
3232   sp_instr *i= get_instr(ip);
3233 
3234   if (i && ! i->marked)
3235     leads->push_front(i);
3236 }
3237 
3238 void
3239 sp_head::opt_mark()
3240 {
3241   uint ip;
3242   sp_instr *i;
3243   List<sp_instr> leads;
3244 
3245   /*
3246     Forward flow analysis algorithm in the instruction graph:
3247     - first, add the entry point in the graph (the first instruction) to the
3248       'leads' list of paths to explore.
3249     - while there are still leads to explore:
3250       - pick one lead, and follow the path forward. Mark instruction reached.
3251         Stop only if the end of the routine is reached, or the path converge
3252         to code already explored (marked).
3253       - while following a path, collect in the 'leads' list any fork to
3254         another path (caused by conditional jumps instructions), so that these
3255         paths can be explored as well.
3256   */
3257 
3258   /* Add the entry point */
3259   i= get_instr(0);
3260   leads.push_front(i);
3261 
3262   /* For each path of code ... */
3263   while (leads.elements != 0)
3264   {
3265     i= leads.pop();
3266 
3267     /* Mark the entire path, collecting new leads. */
3268     while (i && ! i->marked)
3269     {
3270       ip= i->opt_mark(this, & leads);
3271       i= get_instr(ip);
3272     }
3273   }
3274 }
3275 
3276 
3277 #ifndef DBUG_OFF
3278 /**
3279   Return the routine instructions as a result set.
3280   @return
3281     0 if ok, !=0 on error.
3282 */
3283 
3284 int
3285 sp_head::show_routine_code(THD *thd)
3286 {
3287   Protocol *protocol= thd->protocol;
3288   char buff[2048];
3289   String buffer(buff, sizeof(buff), system_charset_info);
3290   List<Item> field_list;
3291   sp_instr *i;
3292   bool full_access;
3293   int res= 0;
3294   uint ip;
3295   DBUG_ENTER("sp_head::show_routine_code");
3296   DBUG_PRINT("info", ("procedure: %s", m_name.str));
3297 
3298   if (check_show_routine_access(thd, this, &full_access) || !full_access)
3299     DBUG_RETURN(1);
3300 
3301   field_list.push_back(new (thd->mem_root) Item_uint(thd, "Pos", 9),
3302                        thd->mem_root);
3303   // 1024 is for not to confuse old clients
3304   field_list.push_back(new (thd->mem_root)
3305                        Item_empty_string(thd, "Instruction",
3306                                          MY_MAX(buffer.length(), 1024)),
3307                        thd->mem_root);
3308   if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS |
3309                                          Protocol::SEND_EOF))
3310     DBUG_RETURN(1);
3311 
3312   for (ip= 0; (i = get_instr(ip)) ; ip++)
3313   {
3314     /*
3315       Consistency check. If these are different something went wrong
3316       during optimization.
3317     */
3318     if (ip != i->m_ip)
3319     {
3320       const char *format= "Instruction at position %u has m_ip=%u";
3321       char tmp[sizeof(format) + 2*SP_INSTR_UINT_MAXLEN + 1];
3322 
3323       my_snprintf(tmp, sizeof(tmp), format, ip, i->m_ip);
3324       /*
3325         Since this is for debugging purposes only, we don't bother to
3326         introduce a special error code for it.
3327       */
3328       push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, tmp);
3329     }
3330     protocol->prepare_for_resend();
3331     protocol->store_long(ip);
3332 
3333     buffer.set("", 0, system_charset_info);
3334     i->print(&buffer);
3335     protocol->store(buffer.ptr(), buffer.length(), system_charset_info);
3336     if ((res= protocol->write()))
3337       break;
3338   }
3339 
3340   if (!res)
3341     my_eof(thd);
3342 
3343   DBUG_RETURN(res);
3344 }
3345 #endif // ifndef DBUG_OFF
3346 
3347 
3348 /**
3349   Prepare LEX and thread for execution of instruction, if requested open
3350   and lock LEX's tables, execute instruction's core function, perform
3351   cleanup afterwards.
3352 
3353   @param thd           thread context
3354   @param nextp         out - next instruction
3355   @param open_tables   if TRUE then check read access to tables in LEX's table
3356                        list and open and lock them (used in instructions which
3357                        need to calculate some expression and don't execute
3358                        complete statement).
3359   @param sp_instr      instruction for which we prepare context, and which core
3360                        function execute by calling its exec_core() method.
3361 
3362   @note
3363     We are not saving/restoring some parts of THD which may need this because
3364     we do this once for whole routine execution in sp_head::execute().
3365 
3366   @return
3367     0/non-0 - Success/Failure
3368 */
3369 
3370 int
3371 sp_lex_keeper::reset_lex_and_exec_core(THD *thd, uint *nextp,
3372                                        bool open_tables, sp_instr* instr)
3373 {
3374   int res= 0;
3375   DBUG_ENTER("reset_lex_and_exec_core");
3376 
3377   /*
3378     The flag is saved at the entry to the following substatement.
3379     It's reset further in the common code part.
3380     It's merged with the saved parent's value at the exit of this func.
3381   */
3382   bool parent_modified_non_trans_table=
3383     thd->transaction.stmt.modified_non_trans_table;
3384   unsigned int parent_unsafe_rollback_flags=
3385     thd->transaction.stmt.m_unsafe_rollback_flags;
3386   thd->transaction.stmt.modified_non_trans_table= FALSE;
3387   thd->transaction.stmt.m_unsafe_rollback_flags= 0;
3388 
3389   DBUG_ASSERT(!thd->derived_tables);
3390   DBUG_ASSERT(thd->Item_change_list::is_empty());
3391   /*
3392     Use our own lex.
3393     We should not save old value since it is saved/restored in
3394     sp_head::execute() when we are entering/leaving routine.
3395   */
3396   thd->lex= m_lex;
3397 
3398   thd->set_query_id(next_query_id());
3399 
3400   if (thd->locked_tables_mode <= LTM_LOCK_TABLES)
3401   {
3402     /*
3403       This statement will enter/leave prelocked mode on its own.
3404       Entering prelocked mode changes table list and related members
3405       of LEX, so we'll need to restore them.
3406     */
3407     if (lex_query_tables_own_last)
3408     {
3409       /*
3410         We've already entered/left prelocked mode with this statement.
3411         Attach the list of tables that need to be prelocked and mark m_lex
3412         as having such list attached.
3413       */
3414       *lex_query_tables_own_last= prelocking_tables;
3415       m_lex->mark_as_requiring_prelocking(lex_query_tables_own_last);
3416     }
3417   }
3418 
3419   reinit_stmt_before_use(thd, m_lex);
3420 
3421 #ifndef EMBEDDED_LIBRARY
3422   /*
3423     If there was instruction which changed tracking state,
3424     the result of changed tracking state send to client in OK packed.
3425     So it changes result sent to client and probably can be different
3426     independent on query text. So we can't cache such results.
3427   */
3428   if ((thd->client_capabilities & CLIENT_SESSION_TRACK) &&
3429       (thd->server_status & SERVER_SESSION_STATE_CHANGED))
3430     thd->lex->safe_to_cache_query= 0;
3431 #endif
3432 
3433   if (open_tables)
3434     res= instr->exec_open_and_lock_tables(thd, m_lex->query_tables);
3435 
3436   if (likely(!res))
3437   {
3438     res= instr->exec_core(thd, nextp);
3439     DBUG_PRINT("info",("exec_core returned: %d", res));
3440   }
3441 
3442   /*
3443     Call after unit->cleanup() to close open table
3444     key read.
3445   */
3446   if (open_tables)
3447   {
3448     m_lex->unit.cleanup();
3449     /* Here we also commit or rollback the current statement. */
3450     if (! thd->in_sub_stmt)
3451     {
3452       thd->get_stmt_da()->set_overwrite_status(true);
3453       thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
3454       thd->get_stmt_da()->set_overwrite_status(false);
3455     }
3456     close_thread_tables(thd);
3457     thd_proc_info(thd, 0);
3458 
3459     if (! thd->in_sub_stmt)
3460     {
3461       if (thd->transaction_rollback_request)
3462       {
3463         trans_rollback_implicit(thd);
3464         thd->release_transactional_locks();
3465       }
3466       else if (! thd->in_multi_stmt_transaction_mode())
3467         thd->release_transactional_locks();
3468       else
3469         thd->mdl_context.release_statement_locks();
3470     }
3471   }
3472   //TODO: why is this here if log_slow_query is in sp_instr_stmt_execute?
3473   delete_explain_query(m_lex);
3474 
3475   if (m_lex->query_tables_own_last)
3476   {
3477     /*
3478       We've entered and left prelocking mode when executing statement
3479       stored in m_lex.
3480       m_lex->query_tables(->next_global)* list now has a 'tail' - a list
3481       of tables that are added for prelocking. (If this is the first
3482       execution, the 'tail' was added by open_tables(), otherwise we've
3483       attached it above in this function).
3484       Now we'll save the 'tail', and detach it.
3485     */
3486     lex_query_tables_own_last= m_lex->query_tables_own_last;
3487     prelocking_tables= *lex_query_tables_own_last;
3488     *lex_query_tables_own_last= NULL;
3489     m_lex->mark_as_requiring_prelocking(NULL);
3490   }
3491   thd->rollback_item_tree_changes();
3492   /*
3493     Update the state of the active arena if no errors on
3494     open_tables stage.
3495   */
3496   if (likely(!res) || likely(!thd->is_error()))
3497     thd->stmt_arena->state= Query_arena::STMT_EXECUTED;
3498 
3499   /*
3500     Merge here with the saved parent's values
3501     what is needed from the substatement gained
3502   */
3503   thd->transaction.stmt.modified_non_trans_table |= parent_modified_non_trans_table;
3504   thd->transaction.stmt.m_unsafe_rollback_flags |= parent_unsafe_rollback_flags;
3505 
3506   TRANSACT_TRACKER(add_trx_state_from_thd(thd));
3507 
3508   /*
3509     Unlike for PS we should not call Item's destructors for newly created
3510     items after execution of each instruction in stored routine. This is
3511     because SP often create Item (like Item_int, Item_string etc...) when
3512     they want to store some value in local variable, pass return value and
3513     etc... So their life time should be longer than one instruction.
3514 
3515     cleanup_items() is called in sp_head::execute()
3516   */
3517   thd->lex->restore_set_statement_var();
3518   DBUG_RETURN(res || thd->is_error());
3519 }
3520 
3521 
3522 int sp_lex_keeper::cursor_reset_lex_and_exec_core(THD *thd, uint *nextp,
3523                                                   bool open_tables,
3524                                                   sp_instr *instr)
3525 {
3526   Query_arena *old_arena= thd->stmt_arena;
3527   /*
3528     Get the Query_arena from the cursor statement LEX, which contains
3529     the free_list of the query, so new items (if any) are stored in
3530     the right free_list, and we can cleanup after each cursor operation,
3531     e.g. open or cursor_copy_struct (for cursor%ROWTYPE variables).
3532   */
3533   thd->stmt_arena= m_lex->query_arena();
3534   int res= reset_lex_and_exec_core(thd, nextp, open_tables, instr);
3535   cleanup_items(thd->stmt_arena->free_list);
3536   thd->stmt_arena= old_arena;
3537   return res;
3538 }
3539 
3540 
3541 /*
3542   sp_instr class functions
3543 */
3544 
3545 int sp_instr::exec_open_and_lock_tables(THD *thd, TABLE_LIST *tables)
3546 {
3547   int result;
3548 
3549   /*
3550     Check whenever we have access to tables for this statement
3551     and open and lock them before executing instructions core function.
3552   */
3553   if (thd->open_temporary_tables(tables) ||
3554       check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE)
3555       || open_and_lock_tables(thd, tables, TRUE, 0))
3556     result= -1;
3557   else
3558     result= 0;
3559   /* Prepare all derived tables/views to catch possible errors. */
3560   if (!result)
3561     result= mysql_handle_derived(thd->lex, DT_PREPARE) ? -1 : 0;
3562 
3563   return result;
3564 }
3565 
3566 uint sp_instr::get_cont_dest() const
3567 {
3568   return (m_ip+1);
3569 }
3570 
3571 
3572 int sp_instr::exec_core(THD *thd, uint *nextp)
3573 {
3574   DBUG_ASSERT(0);
3575   return 0;
3576 }
3577 
3578 /*
3579   sp_instr_stmt class functions
3580 */
3581 
3582 int
3583 sp_instr_stmt::execute(THD *thd, uint *nextp)
3584 {
3585   int res;
3586   bool save_enable_slow_log;
3587   const CSET_STRING query_backup= thd->query_string;
3588   Sub_statement_state backup_state;
3589   DBUG_ENTER("sp_instr_stmt::execute");
3590   DBUG_PRINT("info", ("command: %d", m_lex_keeper.sql_command()));
3591 
3592 #if defined(ENABLED_PROFILING)
3593   /* This s-p instr is profilable and will be captured. */
3594   thd->profiling.set_query_source(m_query.str, m_query.length);
3595 #endif
3596 
3597   save_enable_slow_log= thd->enable_slow_log;
3598   thd->store_slow_query_state(&backup_state);
3599 
3600   if (!(res= alloc_query(thd, m_query.str, m_query.length)) &&
3601       !(res=subst_spvars(thd, this, &m_query)))
3602   {
3603     /*
3604       (the order of query cache and subst_spvars calls is irrelevant because
3605       queries with SP vars can't be cached)
3606     */
3607     general_log_write(thd, COM_QUERY, thd->query(), thd->query_length());
3608 
3609     if (query_cache_send_result_to_client(thd, thd->query(),
3610                                           thd->query_length()) <= 0)
3611     {
3612       thd->reset_slow_query_state();
3613       res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this);
3614       bool log_slow= !res && thd->enable_slow_log;
3615 
3616       /* Finalize server status flags after executing a statement. */
3617       if (log_slow || thd->get_stmt_da()->is_eof())
3618         thd->update_server_status();
3619 
3620       if (thd->get_stmt_da()->is_eof())
3621         thd->protocol->end_statement();
3622 
3623       query_cache_end_of_result(thd);
3624 
3625       mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
3626                           thd->get_stmt_da()->is_error() ?
3627                                  thd->get_stmt_da()->sql_errno() : 0,
3628                           command_name[COM_QUERY].str);
3629 
3630       if (log_slow)
3631         log_slow_statement(thd);
3632 
3633       /*
3634         Restore enable_slow_log, that can be changed by a admin or call
3635         command
3636       */
3637       thd->enable_slow_log= save_enable_slow_log;
3638 
3639       /* Add the number of rows to thd for the 'call' statistics */
3640       thd->add_slow_query_state(&backup_state);
3641     }
3642     else
3643     {
3644       /* change statistics */
3645       enum_sql_command save_sql_command= thd->lex->sql_command;
3646       thd->lex->sql_command= SQLCOM_SELECT;
3647       status_var_increment(thd->status_var.com_stat[SQLCOM_SELECT]);
3648       thd->update_stats();
3649       thd->lex->sql_command= save_sql_command;
3650       *nextp= m_ip+1;
3651     }
3652     thd->set_query(query_backup);
3653     thd->query_name_consts= 0;
3654 
3655     if (likely(!thd->is_error()))
3656     {
3657       res= 0;
3658       thd->get_stmt_da()->reset_diagnostics_area();
3659     }
3660   }
3661 
3662   DBUG_RETURN(res || thd->is_error());
3663 }
3664 
3665 
3666 void
3667 sp_instr_stmt::print(String *str)
3668 {
3669   size_t i, len;
3670 
3671   /* stmt CMD "..." */
3672   if (str->reserve(SP_STMT_PRINT_MAXLEN+SP_INSTR_UINT_MAXLEN+8))
3673     return;
3674   str->qs_append(STRING_WITH_LEN("stmt "));
3675   str->qs_append((uint)m_lex_keeper.sql_command());
3676   str->qs_append(STRING_WITH_LEN(" \""));
3677   len= m_query.length;
3678   /*
3679     Print the query string (but not too much of it), just to indicate which
3680     statement it is.
3681   */
3682   if (len > SP_STMT_PRINT_MAXLEN)
3683     len= SP_STMT_PRINT_MAXLEN-3;
3684   /* Copy the query string and replace '\n' with ' ' in the process */
3685   for (i= 0 ; i < len ; i++)
3686   {
3687     char c= m_query.str[i];
3688     if (c == '\n')
3689       c= ' ';
3690     str->qs_append(c);
3691   }
3692   if (m_query.length > SP_STMT_PRINT_MAXLEN)
3693     str->qs_append(STRING_WITH_LEN("...")); /* Indicate truncated string */
3694   str->qs_append('"');
3695 }
3696 
3697 
3698 int
3699 sp_instr_stmt::exec_core(THD *thd, uint *nextp)
3700 {
3701   MYSQL_QUERY_EXEC_START(thd->query(),
3702                          thd->thread_id,
3703                          thd->get_db(),
3704                          &thd->security_ctx->priv_user[0],
3705                          (char *)thd->security_ctx->host_or_ip,
3706                          3);
3707   int res= mysql_execute_command(thd);
3708   MYSQL_QUERY_EXEC_DONE(res);
3709   *nextp= m_ip+1;
3710   return res;
3711 }
3712 
3713 
3714 /*
3715   sp_instr_set class functions
3716 */
3717 
3718 int
3719 sp_instr_set::execute(THD *thd, uint *nextp)
3720 {
3721   DBUG_ENTER("sp_instr_set::execute");
3722   DBUG_PRINT("info", ("offset: %u", m_offset));
3723 
3724   DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
3725 }
3726 
3727 
3728 sp_rcontext *sp_instr_set::get_rcontext(THD *thd) const
3729 {
3730   return m_rcontext_handler->get_rcontext(thd->spcont);
3731 }
3732 
3733 
3734 int
3735 sp_instr_set::exec_core(THD *thd, uint *nextp)
3736 {
3737   int res= get_rcontext(thd)->set_variable(thd, m_offset, &m_value);
3738   delete_explain_query(thd->lex);
3739   *nextp = m_ip+1;
3740   return res;
3741 }
3742 
3743 void
3744 sp_instr_set::print(String *str)
3745 {
3746   /* set name@offset ... */
3747   size_t rsrv = SP_INSTR_UINT_MAXLEN+6;
3748   sp_variable *var = m_ctx->find_variable(m_offset);
3749   const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix();
3750 
3751   /* 'var' should always be non-null, but just in case... */
3752   if (var)
3753     rsrv+= var->name.length + prefix->length;
3754   if (str->reserve(rsrv))
3755     return;
3756   str->qs_append(STRING_WITH_LEN("set "));
3757   str->qs_append(prefix->str, prefix->length);
3758   if (var)
3759   {
3760     str->qs_append(&var->name);
3761     str->qs_append('@');
3762   }
3763   str->qs_append(m_offset);
3764   str->qs_append(' ');
3765   m_value->print(str, enum_query_type(QT_ORDINARY |
3766                                       QT_ITEM_ORIGINAL_FUNC_NULLIF));
3767 }
3768 
3769 
3770 /*
3771   sp_instr_set_field class functions
3772 */
3773 
3774 int
3775 sp_instr_set_row_field::exec_core(THD *thd, uint *nextp)
3776 {
3777   int res= get_rcontext(thd)->set_variable_row_field(thd, m_offset,
3778                                                      m_field_offset,
3779                                                      &m_value);
3780   delete_explain_query(thd->lex);
3781   *nextp= m_ip + 1;
3782   return res;
3783 }
3784 
3785 
3786 void
3787 sp_instr_set_row_field::print(String *str)
3788 {
3789   /* set name@offset[field_offset] ... */
3790   size_t rsrv= SP_INSTR_UINT_MAXLEN + 6 + 6 + 3;
3791   sp_variable *var= m_ctx->find_variable(m_offset);
3792   const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix();
3793   DBUG_ASSERT(var);
3794   DBUG_ASSERT(var->field_def.is_row());
3795   const Column_definition *def=
3796     var->field_def.row_field_definitions()->elem(m_field_offset);
3797   DBUG_ASSERT(def);
3798 
3799   rsrv+= var->name.length + def->field_name.length + prefix->length;
3800   if (str->reserve(rsrv))
3801     return;
3802   str->qs_append(STRING_WITH_LEN("set "));
3803   str->qs_append(prefix);
3804   str->qs_append(&var->name);
3805   str->qs_append('.');
3806   str->qs_append(&def->field_name);
3807   str->qs_append('@');
3808   str->qs_append(m_offset);
3809   str->qs_append('[');
3810   str->qs_append(m_field_offset);
3811   str->qs_append(']');
3812   str->qs_append(' ');
3813   m_value->print(str, enum_query_type(QT_ORDINARY |
3814                                       QT_ITEM_ORIGINAL_FUNC_NULLIF));
3815 }
3816 
3817 
3818 /*
3819   sp_instr_set_field_by_name class functions
3820 */
3821 
3822 int
3823 sp_instr_set_row_field_by_name::exec_core(THD *thd, uint *nextp)
3824 {
3825   int res= get_rcontext(thd)->set_variable_row_field_by_name(thd, m_offset,
3826                                                              m_field_name,
3827                                                              &m_value);
3828   delete_explain_query(thd->lex);
3829   *nextp= m_ip + 1;
3830   return res;
3831 }
3832 
3833 
3834 void
3835 sp_instr_set_row_field_by_name::print(String *str)
3836 {
3837   /* set name.field@offset["field"] ... */
3838   size_t rsrv= SP_INSTR_UINT_MAXLEN + 6 + 6 + 3 + 2;
3839   sp_variable *var= m_ctx->find_variable(m_offset);
3840   const LEX_CSTRING *prefix= m_rcontext_handler->get_name_prefix();
3841   DBUG_ASSERT(var);
3842   DBUG_ASSERT(var->field_def.is_table_rowtype_ref() ||
3843               var->field_def.is_cursor_rowtype_ref());
3844 
3845   rsrv+= var->name.length + 2 * m_field_name.length + prefix->length;
3846   if (str->reserve(rsrv))
3847     return;
3848   str->qs_append(STRING_WITH_LEN("set "));
3849   str->qs_append(prefix);
3850   str->qs_append(&var->name);
3851   str->qs_append('.');
3852   str->qs_append(&m_field_name);
3853   str->qs_append('@');
3854   str->qs_append(m_offset);
3855   str->qs_append("[\"",2);
3856   str->qs_append(&m_field_name);
3857   str->qs_append("\"]",2);
3858   str->qs_append(' ');
3859   m_value->print(str, enum_query_type(QT_ORDINARY |
3860                                       QT_ITEM_ORIGINAL_FUNC_NULLIF));
3861 }
3862 
3863 
3864 /*
3865   sp_instr_set_trigger_field class functions
3866 */
3867 
3868 int
3869 sp_instr_set_trigger_field::execute(THD *thd, uint *nextp)
3870 {
3871   DBUG_ENTER("sp_instr_set_trigger_field::execute");
3872   thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
3873   DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
3874 }
3875 
3876 
3877 int
3878 sp_instr_set_trigger_field::exec_core(THD *thd, uint *nextp)
3879 {
3880   bool sav_abort_on_warning= thd->abort_on_warning;
3881   thd->abort_on_warning= thd->is_strict_mode() && !thd->lex->ignore;
3882   const int res= (trigger_field->set_value(thd, &value) ? -1 : 0);
3883   thd->abort_on_warning= sav_abort_on_warning;
3884   *nextp = m_ip+1;
3885   return res;
3886 }
3887 
3888 void
3889 sp_instr_set_trigger_field::print(String *str)
3890 {
3891   str->append(STRING_WITH_LEN("set_trigger_field "));
3892   trigger_field->print(str, enum_query_type(QT_ORDINARY |
3893                                             QT_ITEM_ORIGINAL_FUNC_NULLIF));
3894   str->append(STRING_WITH_LEN(":="));
3895   value->print(str, enum_query_type(QT_ORDINARY |
3896                                     QT_ITEM_ORIGINAL_FUNC_NULLIF));
3897 }
3898 
3899 /*
3900   sp_instr_opt_meta
3901 */
3902 
3903 uint sp_instr_opt_meta::get_cont_dest() const
3904 {
3905   return m_cont_dest;
3906 }
3907 
3908 
3909 /*
3910  sp_instr_jump class functions
3911 */
3912 
3913 int
3914 sp_instr_jump::execute(THD *thd, uint *nextp)
3915 {
3916   DBUG_ENTER("sp_instr_jump::execute");
3917   DBUG_PRINT("info", ("destination: %u", m_dest));
3918 
3919   *nextp= m_dest;
3920   DBUG_RETURN(0);
3921 }
3922 
3923 void
3924 sp_instr_jump::print(String *str)
3925 {
3926   /* jump dest */
3927   if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
3928     return;
3929   str->qs_append(STRING_WITH_LEN("jump "));
3930   str->qs_append(m_dest);
3931 }
3932 
3933 uint
3934 sp_instr_jump::opt_mark(sp_head *sp, List<sp_instr> *leads)
3935 {
3936   m_dest= opt_shortcut_jump(sp, this);
3937   if (m_dest != m_ip+1)   /* Jumping to following instruction? */
3938     marked= 1;
3939   m_optdest= sp->get_instr(m_dest);
3940   return m_dest;
3941 }
3942 
3943 uint
3944 sp_instr_jump::opt_shortcut_jump(sp_head *sp, sp_instr *start)
3945 {
3946   uint dest= m_dest;
3947   sp_instr *i;
3948 
3949   while ((i= sp->get_instr(dest)))
3950   {
3951     uint ndest;
3952 
3953     if (start == i || this == i)
3954       break;
3955     ndest= i->opt_shortcut_jump(sp, start);
3956     if (ndest == dest)
3957       break;
3958     dest= ndest;
3959   }
3960   return dest;
3961 }
3962 
3963 void
3964 sp_instr_jump::opt_move(uint dst, List<sp_instr> *bp)
3965 {
3966   if (m_dest > m_ip)
3967     bp->push_back(this);      // Forward
3968   else if (m_optdest)
3969     m_dest= m_optdest->m_ip;  // Backward
3970   m_ip= dst;
3971 }
3972 
3973 
3974 /*
3975   sp_instr_jump_if_not class functions
3976 */
3977 
3978 int
3979 sp_instr_jump_if_not::execute(THD *thd, uint *nextp)
3980 {
3981   DBUG_ENTER("sp_instr_jump_if_not::execute");
3982   DBUG_PRINT("info", ("destination: %u", m_dest));
3983   DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
3984 }
3985 
3986 
3987 int
3988 sp_instr_jump_if_not::exec_core(THD *thd, uint *nextp)
3989 {
3990   Item *it;
3991   int res;
3992 
3993   it= thd->sp_prepare_func_item(&m_expr);
3994   if (! it)
3995   {
3996     res= -1;
3997   }
3998   else
3999   {
4000     res= 0;
4001     if (! it->val_bool())
4002       *nextp = m_dest;
4003     else
4004       *nextp = m_ip+1;
4005   }
4006 
4007   return res;
4008 }
4009 
4010 
4011 void
4012 sp_instr_jump_if_not::print(String *str)
4013 {
4014   /* jump_if_not dest(cont) ... */
4015   if (str->reserve(2*SP_INSTR_UINT_MAXLEN+14+32)) // Add some for the expr. too
4016     return;
4017   str->qs_append(STRING_WITH_LEN("jump_if_not "));
4018   str->qs_append(m_dest);
4019   str->qs_append('(');
4020   str->qs_append(m_cont_dest);
4021   str->qs_append(STRING_WITH_LEN(") "));
4022   m_expr->print(str, enum_query_type(QT_ORDINARY |
4023                                      QT_ITEM_ORIGINAL_FUNC_NULLIF));
4024 }
4025 
4026 
4027 uint
4028 sp_instr_jump_if_not::opt_mark(sp_head *sp, List<sp_instr> *leads)
4029 {
4030   sp_instr *i;
4031 
4032   marked= 1;
4033   if ((i= sp->get_instr(m_dest)))
4034   {
4035     m_dest= i->opt_shortcut_jump(sp, this);
4036     m_optdest= sp->get_instr(m_dest);
4037   }
4038   sp->add_mark_lead(m_dest, leads);
4039   if ((i= sp->get_instr(m_cont_dest)))
4040   {
4041     m_cont_dest= i->opt_shortcut_jump(sp, this);
4042     m_cont_optdest= sp->get_instr(m_cont_dest);
4043   }
4044   sp->add_mark_lead(m_cont_dest, leads);
4045   return m_ip+1;
4046 }
4047 
4048 void
4049 sp_instr_jump_if_not::opt_move(uint dst, List<sp_instr> *bp)
4050 {
4051   /*
4052     cont. destinations may point backwards after shortcutting jumps
4053     during the mark phase. If it's still pointing forwards, only
4054     push this for backpatching if sp_instr_jump::opt_move() will not
4055     do it (i.e. if the m_dest points backwards).
4056    */
4057   if (m_cont_dest > m_ip)
4058   {                             // Forward
4059     if (m_dest < m_ip)
4060       bp->push_back(this);
4061   }
4062   else if (m_cont_optdest)
4063     m_cont_dest= m_cont_optdest->m_ip; // Backward
4064   /* This will take care of m_dest and m_ip */
4065   sp_instr_jump::opt_move(dst, bp);
4066 }
4067 
4068 
4069 /*
4070   sp_instr_freturn class functions
4071 */
4072 
4073 int
4074 sp_instr_freturn::execute(THD *thd, uint *nextp)
4075 {
4076   DBUG_ENTER("sp_instr_freturn::execute");
4077   DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
4078 }
4079 
4080 
4081 int
4082 sp_instr_freturn::exec_core(THD *thd, uint *nextp)
4083 {
4084   /*
4085     RETURN is a "procedure statement" (in terms of the SQL standard).
4086     That means, Diagnostics Area should be clean before its execution.
4087   */
4088 
4089   if (!(thd->variables.sql_mode & MODE_ORACLE))
4090   {
4091     /*
4092       Don't clean warnings in ORACLE mode,
4093       as they are needed for SQLCODE and SQLERRM:
4094         BEGIN
4095           SELECT a INTO a FROM t1;
4096           RETURN 'No exception ' || SQLCODE || ' ' || SQLERRM;
4097         EXCEPTION WHEN NO_DATA_FOUND THEN
4098           RETURN 'Exception ' || SQLCODE || ' ' || SQLERRM;
4099         END;
4100     */
4101     Diagnostics_area *da= thd->get_stmt_da();
4102     da->clear_warning_info(da->warning_info_id());
4103   }
4104 
4105   /*
4106     Change <next instruction pointer>, so that this will be the last
4107     instruction in the stored function.
4108   */
4109 
4110   *nextp= UINT_MAX;
4111 
4112   /*
4113     Evaluate the value of return expression and store it in current runtime
4114     context.
4115 
4116     NOTE: It's necessary to evaluate result item right here, because we must
4117     do it in scope of execution the current context/block.
4118   */
4119 
4120   return thd->spcont->set_return_value(thd, &m_value);
4121 }
4122 
4123 void
4124 sp_instr_freturn::print(String *str)
4125 {
4126   /* freturn type expr... */
4127   if (str->reserve(1024+8+32)) // Add some for the expr. too
4128     return;
4129   str->qs_append(STRING_WITH_LEN("freturn "));
4130   str->qs_append(m_type_handler->name().ptr());
4131   str->qs_append(' ');
4132   m_value->print(str, enum_query_type(QT_ORDINARY |
4133                                       QT_ITEM_ORIGINAL_FUNC_NULLIF));
4134 }
4135 
4136 /*
4137   sp_instr_hpush_jump class functions
4138 */
4139 
4140 int
4141 sp_instr_hpush_jump::execute(THD *thd, uint *nextp)
4142 {
4143   DBUG_ENTER("sp_instr_hpush_jump::execute");
4144 
4145   int ret= thd->spcont->push_handler(this);
4146 
4147   *nextp= m_dest;
4148 
4149   DBUG_RETURN(ret);
4150 }
4151 
4152 
4153 void
4154 sp_instr_hpush_jump::print(String *str)
4155 {
4156   /* hpush_jump dest fsize type */
4157   if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 21))
4158     return;
4159 
4160   str->qs_append(STRING_WITH_LEN("hpush_jump "));
4161   str->qs_append(m_dest);
4162   str->qs_append(' ');
4163   str->qs_append(m_frame);
4164 
4165   switch (m_handler->type) {
4166   case sp_handler::EXIT:
4167     str->qs_append(STRING_WITH_LEN(" EXIT"));
4168     break;
4169   case sp_handler::CONTINUE:
4170     str->qs_append(STRING_WITH_LEN(" CONTINUE"));
4171     break;
4172   default:
4173     // The handler type must be either CONTINUE or EXIT.
4174     DBUG_ASSERT(0);
4175   }
4176 }
4177 
4178 
4179 uint
4180 sp_instr_hpush_jump::opt_mark(sp_head *sp, List<sp_instr> *leads)
4181 {
4182   sp_instr *i;
4183 
4184   marked= 1;
4185   if ((i= sp->get_instr(m_dest)))
4186   {
4187     m_dest= i->opt_shortcut_jump(sp, this);
4188     m_optdest= sp->get_instr(m_dest);
4189   }
4190   sp->add_mark_lead(m_dest, leads);
4191 
4192   /*
4193     For continue handlers, all instructions in the scope of the handler
4194     are possible leads. For example, the instruction after freturn might
4195     be executed if the freturn triggers the condition handled by the
4196     continue handler.
4197 
4198     m_dest marks the start of the handler scope. It's added as a lead
4199     above, so we start on m_dest+1 here.
4200     m_opt_hpop is the hpop marking the end of the handler scope.
4201   */
4202   if (m_handler->type == sp_handler::CONTINUE)
4203   {
4204     for (uint scope_ip= m_dest+1; scope_ip <= m_opt_hpop; scope_ip++)
4205       sp->add_mark_lead(scope_ip, leads);
4206   }
4207 
4208   return m_ip+1;
4209 }
4210 
4211 
4212 /*
4213   sp_instr_hpop class functions
4214 */
4215 
4216 int
4217 sp_instr_hpop::execute(THD *thd, uint *nextp)
4218 {
4219   DBUG_ENTER("sp_instr_hpop::execute");
4220   thd->spcont->pop_handlers(m_count);
4221   *nextp= m_ip+1;
4222   DBUG_RETURN(0);
4223 }
4224 
4225 void
4226 sp_instr_hpop::print(String *str)
4227 {
4228   /* hpop count */
4229   if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
4230     return;
4231   str->qs_append(STRING_WITH_LEN("hpop "));
4232   str->qs_append(m_count);
4233 }
4234 
4235 
4236 /*
4237   sp_instr_hreturn class functions
4238 */
4239 
4240 int
4241 sp_instr_hreturn::execute(THD *thd, uint *nextp)
4242 {
4243   DBUG_ENTER("sp_instr_hreturn::execute");
4244 
4245   uint continue_ip= thd->spcont->exit_handler(thd->get_stmt_da());
4246 
4247   *nextp= m_dest ? m_dest : continue_ip;
4248 
4249   DBUG_RETURN(0);
4250 }
4251 
4252 
4253 void
4254 sp_instr_hreturn::print(String *str)
4255 {
4256   /* hreturn framesize dest */
4257   if (str->reserve(SP_INSTR_UINT_MAXLEN*2 + 9))
4258     return;
4259   str->qs_append(STRING_WITH_LEN("hreturn "));
4260   if (m_dest)
4261   {
4262     // NOTE: this is legacy: hreturn instruction for EXIT handler
4263     // should print out 0 as frame index.
4264     str->qs_append(STRING_WITH_LEN("0 "));
4265     str->qs_append(m_dest);
4266   }
4267   else
4268   {
4269     str->qs_append(m_frame);
4270   }
4271 }
4272 
4273 
4274 uint
4275 sp_instr_hreturn::opt_mark(sp_head *sp, List<sp_instr> *leads)
4276 {
4277   marked= 1;
4278 
4279   if (m_dest)
4280   {
4281     /*
4282       This is an EXIT handler; next instruction step is in m_dest.
4283      */
4284     return m_dest;
4285   }
4286 
4287   /*
4288     This is a CONTINUE handler; next instruction step will come from
4289     the handler stack and not from opt_mark.
4290    */
4291   return UINT_MAX;
4292 }
4293 
4294 
4295 /*
4296   sp_instr_cpush class functions
4297 */
4298 
4299 int
4300 sp_instr_cpush::execute(THD *thd, uint *nextp)
4301 {
4302   DBUG_ENTER("sp_instr_cpush::execute");
4303 
4304   sp_cursor::reset(thd, &m_lex_keeper);
4305   m_lex_keeper.disable_query_cache();
4306   thd->spcont->push_cursor(this);
4307 
4308   *nextp= m_ip+1;
4309 
4310   DBUG_RETURN(false);
4311 }
4312 
4313 
4314 void
4315 sp_instr_cpush::print(String *str)
4316 {
4317   const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor);
4318 
4319   /* cpush name@offset */
4320   size_t rsrv= SP_INSTR_UINT_MAXLEN+7;
4321 
4322   if (cursor_name)
4323     rsrv+= cursor_name->length;
4324   if (str->reserve(rsrv))
4325     return;
4326   str->qs_append(STRING_WITH_LEN("cpush "));
4327   if (cursor_name)
4328   {
4329     str->qs_append(cursor_name->str, cursor_name->length);
4330     str->qs_append('@');
4331   }
4332   str->qs_append(m_cursor);
4333 }
4334 
4335 
4336 /*
4337   sp_instr_cpop class functions
4338 */
4339 
4340 int
4341 sp_instr_cpop::execute(THD *thd, uint *nextp)
4342 {
4343   DBUG_ENTER("sp_instr_cpop::execute");
4344   thd->spcont->pop_cursors(thd, m_count);
4345   *nextp= m_ip+1;
4346   DBUG_RETURN(0);
4347 }
4348 
4349 
4350 void
4351 sp_instr_cpop::print(String *str)
4352 {
4353   /* cpop count */
4354   if (str->reserve(SP_INSTR_UINT_MAXLEN+5))
4355     return;
4356   str->qs_append(STRING_WITH_LEN("cpop "));
4357   str->qs_append(m_count);
4358 }
4359 
4360 
4361 /*
4362   sp_instr_copen class functions
4363 */
4364 
4365 /**
4366   @todo
4367     Assert that we either have an error or a cursor
4368 */
4369 
4370 int
4371 sp_instr_copen::execute(THD *thd, uint *nextp)
4372 {
4373   /*
4374     We don't store a pointer to the cursor in the instruction to be
4375     able to reuse the same instruction among different threads in future.
4376   */
4377   sp_cursor *c= thd->spcont->get_cursor(m_cursor);
4378   int res;
4379   DBUG_ENTER("sp_instr_copen::execute");
4380 
4381   if (! c)
4382     res= -1;
4383   else
4384   {
4385     sp_lex_keeper *lex_keeper= c->get_lex_keeper();
4386     res= lex_keeper->cursor_reset_lex_and_exec_core(thd, nextp, FALSE, this);
4387     /* TODO: Assert here that we either have an error or a cursor */
4388   }
4389   DBUG_RETURN(res);
4390 }
4391 
4392 
4393 int
4394 sp_instr_copen::exec_core(THD *thd, uint *nextp)
4395 {
4396   sp_cursor *c= thd->spcont->get_cursor(m_cursor);
4397   int res= c->open(thd);
4398   *nextp= m_ip+1;
4399   return res;
4400 }
4401 
4402 void
4403 sp_instr_copen::print(String *str)
4404 {
4405   const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor);
4406 
4407   /* copen name@offset */
4408   size_t rsrv= SP_INSTR_UINT_MAXLEN+7;
4409 
4410   if (cursor_name)
4411     rsrv+= cursor_name->length;
4412   if (str->reserve(rsrv))
4413     return;
4414   str->qs_append(STRING_WITH_LEN("copen "));
4415   if (cursor_name)
4416   {
4417     str->qs_append(cursor_name->str, cursor_name->length);
4418     str->qs_append('@');
4419   }
4420   str->qs_append(m_cursor);
4421 }
4422 
4423 
4424 /*
4425   sp_instr_cclose class functions
4426 */
4427 
4428 int
4429 sp_instr_cclose::execute(THD *thd, uint *nextp)
4430 {
4431   sp_cursor *c= thd->spcont->get_cursor(m_cursor);
4432   int res;
4433   DBUG_ENTER("sp_instr_cclose::execute");
4434 
4435   if (! c)
4436     res= -1;
4437   else
4438     res= c->close(thd);
4439   *nextp= m_ip+1;
4440   DBUG_RETURN(res);
4441 }
4442 
4443 
4444 void
4445 sp_instr_cclose::print(String *str)
4446 {
4447   const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor);
4448 
4449   /* cclose name@offset */
4450   size_t rsrv= SP_INSTR_UINT_MAXLEN+8;
4451 
4452   if (cursor_name)
4453     rsrv+= cursor_name->length;
4454   if (str->reserve(rsrv))
4455     return;
4456   str->qs_append(STRING_WITH_LEN("cclose "));
4457   if (cursor_name)
4458   {
4459     str->qs_append(cursor_name->str, cursor_name->length);
4460     str->qs_append('@');
4461   }
4462   str->qs_append(m_cursor);
4463 }
4464 
4465 
4466 /*
4467   sp_instr_cfetch class functions
4468 */
4469 
4470 int
4471 sp_instr_cfetch::execute(THD *thd, uint *nextp)
4472 {
4473   sp_cursor *c= thd->spcont->get_cursor(m_cursor);
4474   int res;
4475   Query_arena backup_arena;
4476   DBUG_ENTER("sp_instr_cfetch::execute");
4477 
4478   res= c ? c->fetch(thd, &m_varlist, m_error_on_no_data) : -1;
4479 
4480   *nextp= m_ip+1;
4481   DBUG_RETURN(res);
4482 }
4483 
4484 
4485 void
4486 sp_instr_cfetch::print(String *str)
4487 {
4488   List_iterator_fast<sp_variable> li(m_varlist);
4489   sp_variable *pv;
4490   const LEX_CSTRING *cursor_name= m_ctx->find_cursor(m_cursor);
4491 
4492   /* cfetch name@offset vars... */
4493   size_t rsrv= SP_INSTR_UINT_MAXLEN+8;
4494 
4495   if (cursor_name)
4496     rsrv+= cursor_name->length;
4497   if (str->reserve(rsrv))
4498     return;
4499   str->qs_append(STRING_WITH_LEN("cfetch "));
4500   if (cursor_name)
4501   {
4502     str->qs_append(cursor_name->str, cursor_name->length);
4503     str->qs_append('@');
4504   }
4505   str->qs_append(m_cursor);
4506   while ((pv= li++))
4507   {
4508     if (str->reserve(pv->name.length+SP_INSTR_UINT_MAXLEN+2))
4509       return;
4510     str->qs_append(' ');
4511     str->qs_append(&pv->name);
4512     str->qs_append('@');
4513     str->qs_append(pv->offset);
4514   }
4515 }
4516 
4517 int
4518 sp_instr_agg_cfetch::execute(THD *thd, uint *nextp)
4519 {
4520   DBUG_ENTER("sp_instr_agg_cfetch::execute");
4521   int res= 0;
4522   if (!thd->spcont->instr_ptr)
4523   {
4524     *nextp= m_ip+1;
4525     thd->spcont->instr_ptr= m_ip + 1;
4526   }
4527   else if (!thd->spcont->pause_state)
4528     thd->spcont->pause_state= TRUE;
4529   else
4530   {
4531     thd->spcont->pause_state= FALSE;
4532     if (thd->server_status & SERVER_STATUS_LAST_ROW_SENT)
4533     {
4534       my_message(ER_SP_FETCH_NO_DATA,
4535                  ER_THD(thd, ER_SP_FETCH_NO_DATA), MYF(0));
4536       res= -1;
4537       thd->spcont->quit_func= TRUE;
4538     }
4539     else
4540       *nextp= m_ip + 1;
4541   }
4542   DBUG_RETURN(res);
4543 }
4544 
4545 void
4546 sp_instr_agg_cfetch::print(String *str)
4547 {
4548 
4549   uint rsrv= SP_INSTR_UINT_MAXLEN+11;
4550 
4551   if (str->reserve(rsrv))
4552     return;
4553   str->qs_append(STRING_WITH_LEN("agg_cfetch"));
4554 }
4555 
4556 /*
4557   sp_instr_cursor_copy_struct class functions
4558 */
4559 
4560 /**
4561   This methods processes cursor %ROWTYPE declarations, e.g.:
4562     CURSOR cur IS SELECT * FROM t1;
4563     rec cur%ROWTYPE;
4564   and does the following:
4565   - opens the cursor without copying data (materialization).
4566   - copies the cursor structure to the associated %ROWTYPE variable.
4567 */
4568 
4569 int
4570 sp_instr_cursor_copy_struct::exec_core(THD *thd, uint *nextp)
4571 {
4572   DBUG_ENTER("sp_instr_cursor_copy_struct::exec_core");
4573   int ret= 0;
4574   Item_field_row *row= (Item_field_row*) thd->spcont->get_variable(m_var);
4575   DBUG_ASSERT(row->type_handler() == &type_handler_row);
4576 
4577   /*
4578     Copy structure only once. If the cursor%ROWTYPE variable is declared
4579     inside a LOOP block, it gets its structure on the first loop interation
4580     and remembers the structure for all consequent loop iterations.
4581     It we recreated the structure on every iteration, we would get
4582     potential memory leaks, and it would be less efficient.
4583   */
4584   if (!row->arguments())
4585   {
4586     sp_cursor tmp(thd, &m_lex_keeper, true);
4587     // Open the cursor without copying data
4588     if (!(ret= tmp.open(thd)))
4589     {
4590       Row_definition_list defs;
4591       /*
4592         Create row elements on the caller arena.
4593         It's the same arena that was used during sp_rcontext::create().
4594         This puts cursor%ROWTYPE elements on the same mem_root
4595         where explicit ROW elements and table%ROWTYPE reside:
4596         - tmp.export_structure() allocates new Spvar_definition instances
4597           and their components (such as TYPELIBs).
4598         - row->row_create_items() creates new Item_field instances.
4599         They all are created on the same mem_root.
4600       */
4601       Query_arena current_arena;
4602       thd->set_n_backup_active_arena(thd->spcont->callers_arena, &current_arena);
4603       if (!(ret= tmp.export_structure(thd, &defs)))
4604         row->row_create_items(thd, &defs);
4605       thd->restore_active_arena(thd->spcont->callers_arena, &current_arena);
4606       tmp.close(thd);
4607     }
4608   }
4609   *nextp= m_ip + 1;
4610   DBUG_RETURN(ret);
4611 }
4612 
4613 
4614 int
4615 sp_instr_cursor_copy_struct::execute(THD *thd, uint *nextp)
4616 {
4617   DBUG_ENTER("sp_instr_cursor_copy_struct::execute");
4618   int ret= m_lex_keeper.cursor_reset_lex_and_exec_core(thd, nextp, FALSE, this);
4619   DBUG_RETURN(ret);
4620 }
4621 
4622 
4623 void
4624 sp_instr_cursor_copy_struct::print(String *str)
4625 {
4626   sp_variable *var= m_ctx->find_variable(m_var);
4627   const LEX_CSTRING *name= m_ctx->find_cursor(m_cursor);
4628   str->append(STRING_WITH_LEN("cursor_copy_struct "));
4629   str->append(name);
4630   str->append(' ');
4631   str->append(&var->name);
4632   str->append('@');
4633   str->append_ulonglong(m_var);
4634 }
4635 
4636 
4637 /*
4638   sp_instr_error class functions
4639 */
4640 
4641 int
4642 sp_instr_error::execute(THD *thd, uint *nextp)
4643 {
4644   DBUG_ENTER("sp_instr_error::execute");
4645 
4646   my_message(m_errcode, ER_THD(thd, m_errcode), MYF(0));
4647   *nextp= m_ip+1;
4648   DBUG_RETURN(-1);
4649 }
4650 
4651 
4652 void
4653 sp_instr_error::print(String *str)
4654 {
4655   /* error code */
4656   if (str->reserve(SP_INSTR_UINT_MAXLEN+6))
4657     return;
4658   str->qs_append(STRING_WITH_LEN("error "));
4659   str->qs_append(m_errcode);
4660 }
4661 
4662 
4663 /**************************************************************************
4664   sp_instr_set_case_expr class implementation
4665 **************************************************************************/
4666 
4667 int
4668 sp_instr_set_case_expr::execute(THD *thd, uint *nextp)
4669 {
4670   DBUG_ENTER("sp_instr_set_case_expr::execute");
4671 
4672   DBUG_RETURN(m_lex_keeper.reset_lex_and_exec_core(thd, nextp, TRUE, this));
4673 }
4674 
4675 
4676 int
4677 sp_instr_set_case_expr::exec_core(THD *thd, uint *nextp)
4678 {
4679   int res= thd->spcont->set_case_expr(thd, m_case_expr_id, &m_case_expr);
4680 
4681   if (res && !thd->spcont->get_case_expr(m_case_expr_id))
4682   {
4683     /*
4684       Failed to evaluate the value, the case expression is still not
4685       initialized. Set to NULL so we can continue.
4686     */
4687 
4688     Item *null_item= new (thd->mem_root) Item_null(thd);
4689 
4690     if (!null_item ||
4691         thd->spcont->set_case_expr(thd, m_case_expr_id, &null_item))
4692     {
4693       /* If this also failed, we have to abort. */
4694       my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
4695     }
4696   }
4697   else
4698     *nextp= m_ip+1;
4699 
4700   return res;
4701 }
4702 
4703 
4704 void
4705 sp_instr_set_case_expr::print(String *str)
4706 {
4707   /* set_case_expr (cont) id ... */
4708   str->reserve(2*SP_INSTR_UINT_MAXLEN+18+32); // Add some extra for expr too
4709   str->qs_append(STRING_WITH_LEN("set_case_expr ("));
4710   str->qs_append(m_cont_dest);
4711   str->qs_append(STRING_WITH_LEN(") "));
4712   str->qs_append(m_case_expr_id);
4713   str->qs_append(' ');
4714   m_case_expr->print(str, enum_query_type(QT_ORDINARY |
4715                                           QT_ITEM_ORIGINAL_FUNC_NULLIF));
4716 }
4717 
4718 uint
4719 sp_instr_set_case_expr::opt_mark(sp_head *sp, List<sp_instr> *leads)
4720 {
4721   sp_instr *i;
4722 
4723   marked= 1;
4724   if ((i= sp->get_instr(m_cont_dest)))
4725   {
4726     m_cont_dest= i->opt_shortcut_jump(sp, this);
4727     m_cont_optdest= sp->get_instr(m_cont_dest);
4728   }
4729   sp->add_mark_lead(m_cont_dest, leads);
4730   return m_ip+1;
4731 }
4732 
4733 void
4734 sp_instr_set_case_expr::opt_move(uint dst, List<sp_instr> *bp)
4735 {
4736   if (m_cont_dest > m_ip)
4737     bp->push_back(this);        // Forward
4738   else if (m_cont_optdest)
4739     m_cont_dest= m_cont_optdest->m_ip; // Backward
4740   m_ip= dst;
4741 }
4742 
4743 
4744 /* ------------------------------------------------------------------ */
4745 
4746 
4747 /*
4748   Structure that represent all instances of one table
4749   in optimized multi-set of tables used by routine.
4750 */
4751 
4752 typedef struct st_sp_table
4753 {
4754   /*
4755     Multi-set key:
4756       db_name\0table_name\0alias\0 - for normal tables
4757       db_name\0table_name\0        - for temporary tables
4758   */
4759   LEX_STRING qname;
4760   size_t db_length, table_name_length;
4761   bool temp;               /* true if corresponds to a temporary table */
4762   thr_lock_type lock_type; /* lock type used for prelocking */
4763   uint lock_count;
4764   uint query_lock_count;
4765   uint8 trg_event_map;
4766   my_bool for_insert_data;
4767 } SP_TABLE;
4768 
4769 
4770 uchar *sp_table_key(const uchar *ptr, size_t *plen, my_bool first)
4771 {
4772   SP_TABLE *tab= (SP_TABLE *)ptr;
4773   *plen= tab->qname.length;
4774   return (uchar *)tab->qname.str;
4775 }
4776 
4777 
4778 /**
4779   Merge the list of tables used by some query into the multi-set of
4780   tables used by routine.
4781 
4782   @param thd                 thread context
4783   @param table               table list
4784   @param lex_for_tmp_check   LEX of the query for which we are merging
4785                              table list.
4786 
4787   @note
4788     This method will use LEX provided to check whenever we are creating
4789     temporary table and mark it as such in target multi-set.
4790 
4791   @retval
4792     TRUE    Success
4793   @retval
4794     FALSE   Error
4795 */
4796 
4797 bool
4798 sp_head::merge_table_list(THD *thd, TABLE_LIST *table, LEX *lex_for_tmp_check)
4799 {
4800   SP_TABLE *tab;
4801 
4802   if ((lex_for_tmp_check->sql_command == SQLCOM_DROP_TABLE ||
4803       lex_for_tmp_check->sql_command == SQLCOM_DROP_SEQUENCE) &&
4804       lex_for_tmp_check->tmp_table())
4805     return TRUE;
4806 
4807   for (uint i= 0 ; i < m_sptabs.records ; i++)
4808   {
4809     tab= (SP_TABLE*) my_hash_element(&m_sptabs, i);
4810     tab->query_lock_count= 0;
4811   }
4812 
4813   for (; table ; table= table->next_global)
4814     if (!table->derived && !table->schema_table)
4815     {
4816       /*
4817         Structure of key for the multi-set is "db\0table\0alias\0".
4818         Since "alias" part can have arbitrary length we use String
4819         object to construct the key. By default String will use
4820         buffer allocated on stack with NAME_LEN bytes reserved for
4821         alias, since in most cases it is going to be smaller than
4822         NAME_LEN bytes.
4823       */
4824       char tname_buff[(SAFE_NAME_LEN + 1) * 3];
4825       String tname(tname_buff, sizeof(tname_buff), &my_charset_bin);
4826       uint temp_table_key_length;
4827 
4828       tname.length(0);
4829       tname.append(&table->db);
4830       tname.append('\0');
4831       tname.append(&table->table_name);
4832       tname.append('\0');
4833       temp_table_key_length= tname.length();
4834       tname.append(&table->alias);
4835       tname.append('\0');
4836 
4837       /*
4838         Upgrade the lock type because this table list will be used
4839         only in pre-locked mode, in which DELAYED inserts are always
4840         converted to normal inserts.
4841       */
4842       if (table->lock_type == TL_WRITE_DELAYED)
4843         table->lock_type= TL_WRITE;
4844 
4845       /*
4846         We ignore alias when we check if table was already marked as temporary
4847         (and therefore should not be prelocked). Otherwise we will erroneously
4848         treat table with same name but with different alias as non-temporary.
4849       */
4850       if ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(),
4851                                            tname.length())) ||
4852           ((tab= (SP_TABLE*) my_hash_search(&m_sptabs, (uchar *)tname.ptr(),
4853                                             temp_table_key_length)) &&
4854            tab->temp))
4855       {
4856         if (tab->lock_type < table->lock_type)
4857           tab->lock_type= table->lock_type; // Use the table with the highest lock type
4858         tab->query_lock_count++;
4859         if (tab->query_lock_count > tab->lock_count)
4860           tab->lock_count++;
4861         tab->trg_event_map|= table->trg_event_map;
4862         tab->for_insert_data|= table->for_insert_data;
4863       }
4864       else
4865       {
4866         if (!(tab= (SP_TABLE *)thd->calloc(sizeof(SP_TABLE))))
4867           return FALSE;
4868         if ((lex_for_tmp_check->sql_command == SQLCOM_CREATE_TABLE ||
4869              lex_for_tmp_check->sql_command == SQLCOM_CREATE_SEQUENCE) &&
4870             lex_for_tmp_check->query_tables == table &&
4871             lex_for_tmp_check->tmp_table())
4872         {
4873           tab->temp= TRUE;
4874           tab->qname.length= temp_table_key_length;
4875         }
4876         else
4877           tab->qname.length= tname.length();
4878         tab->qname.str= (char*) thd->memdup(tname.ptr(), tab->qname.length);
4879         if (!tab->qname.str)
4880           return FALSE;
4881         tab->table_name_length= table->table_name.length;
4882         tab->db_length= table->db.length;
4883         tab->lock_type= table->lock_type;
4884         tab->lock_count= tab->query_lock_count= 1;
4885         tab->trg_event_map= table->trg_event_map;
4886         tab->for_insert_data= table->for_insert_data;
4887         if (my_hash_insert(&m_sptabs, (uchar *)tab))
4888           return FALSE;
4889       }
4890     }
4891   return TRUE;
4892 }
4893 
4894 
4895 /**
4896   Add tables used by routine to the table list.
4897 
4898     Converts multi-set of tables used by this routine to table list and adds
4899     this list to the end of table list specified by 'query_tables_last_ptr'.
4900 
4901     Elements of list will be allocated in PS memroot, so this list will be
4902     persistent between PS executions.
4903 
4904   @param[in] thd                        Thread context
4905   @param[in,out] query_tables_last_ptr  Pointer to the next_global member of
4906     last element of the list where tables
4907     will be added (or to its root).
4908   @param[in] belong_to_view             Uppermost view which uses this routine,
4909     0 if none.
4910 
4911   @retval
4912     TRUE    if some elements were added
4913   @retval
4914     FALSE   otherwise.
4915 */
4916 
4917 bool
4918 sp_head::add_used_tables_to_table_list(THD *thd,
4919                                        TABLE_LIST ***query_tables_last_ptr,
4920                                        TABLE_LIST *belong_to_view)
4921 {
4922   uint i;
4923   Query_arena *arena, backup;
4924   bool result= FALSE;
4925   DBUG_ENTER("sp_head::add_used_tables_to_table_list");
4926 
4927   /*
4928     Use persistent arena for table list allocation to be PS/SP friendly.
4929     Note that we also have to copy database/table names and alias to PS/SP
4930     memory since current instance of sp_head object can pass away before
4931     next execution of PS/SP for which tables are added to prelocking list.
4932     This will be fixed by introducing of proper invalidation mechanism
4933     once new TDC is ready.
4934   */
4935   arena= thd->activate_stmt_arena_if_needed(&backup);
4936 
4937   for (i=0 ; i < m_sptabs.records ; i++)
4938   {
4939     char *tab_buff, *key_buff;
4940     SP_TABLE *stab= (SP_TABLE*) my_hash_element(&m_sptabs, i);
4941     LEX_CSTRING db_name;
4942     if (stab->temp)
4943       continue;
4944 
4945     if (!(tab_buff= (char *)thd->alloc(ALIGN_SIZE(sizeof(TABLE_LIST)) *
4946                                         stab->lock_count)) ||
4947         !(key_buff= (char*)thd->memdup(stab->qname.str,
4948                                        stab->qname.length)))
4949       DBUG_RETURN(FALSE);
4950 
4951     db_name.str=    key_buff;
4952     db_name.length= stab->db_length;
4953 
4954 
4955     for (uint j= 0; j < stab->lock_count; j++)
4956     {
4957       TABLE_LIST *table= (TABLE_LIST *)tab_buff;
4958       LEX_CSTRING table_name= { key_buff + stab->db_length + 1,
4959                                 stab->table_name_length };
4960       LEX_CSTRING alias= { table_name.str + table_name.length + 1,
4961                            strlen(table_name.str + table_name.length + 1) };
4962 
4963       table->init_one_table_for_prelocking(&db_name,
4964                                            &table_name,
4965                                            &alias,
4966                                            stab->lock_type,
4967                                            TABLE_LIST::PRELOCK_ROUTINE,
4968                                            belong_to_view,
4969                                            stab->trg_event_map,
4970                                            query_tables_last_ptr,
4971                                            stab->for_insert_data);
4972       tab_buff+= ALIGN_SIZE(sizeof(TABLE_LIST));
4973       result= TRUE;
4974     }
4975   }
4976 
4977   if (arena)
4978     thd->restore_active_arena(arena, &backup);
4979 
4980   DBUG_RETURN(result);
4981 }
4982 
4983 
4984 /**
4985   Simple function for adding an explicitly named (systems) table to
4986   the global table list, e.g. "mysql", "proc".
4987 */
4988 
4989 TABLE_LIST *
4990 sp_add_to_query_tables(THD *thd, LEX *lex,
4991 		       const LEX_CSTRING *db, const LEX_CSTRING *name,
4992                        thr_lock_type locktype,
4993                        enum_mdl_type mdl_type)
4994 {
4995   TABLE_LIST *table;
4996 
4997   if (!(table= (TABLE_LIST *)thd->calloc(sizeof(TABLE_LIST))))
4998     return NULL;
4999   if (!thd->make_lex_string(&table->db, db->str, db->length) ||
5000       !thd->make_lex_string(&table->table_name, name->str, name->length) ||
5001       !thd->make_lex_string(&table->alias, name->str, name->length))
5002     return NULL;
5003 
5004   table->lock_type= locktype;
5005   table->select_lex= lex->current_select;
5006   table->cacheable_table= 1;
5007   table->mdl_request.init(MDL_key::TABLE, table->db.str, table->table_name.str,
5008                           mdl_type, MDL_TRANSACTION);
5009 
5010   lex->add_to_query_tables(table);
5011   return table;
5012 }
5013 
5014 
5015 Item *sp_head::adjust_assignment_source(THD *thd, Item *val, Item *val2)
5016 {
5017   return val ? val : val2 ? val2 : new (thd->mem_root) Item_null(thd);
5018 }
5019 
5020 /**
5021   Helper action for a SET statement.
5022   Used to push a SP local variable into the assignment list.
5023 
5024   @param var_type the SP local variable
5025   @param val      the value being assigned to the variable
5026 
5027   @return TRUE if error, FALSE otherwise.
5028 */
5029 
5030 bool
5031 sp_head::set_local_variable(THD *thd, sp_pcontext *spcont,
5032                             const Sp_rcontext_handler *rh,
5033                             sp_variable *spv, Item *val, LEX *lex,
5034                             bool responsible_to_free_lex)
5035 {
5036   if (!(val= adjust_assignment_source(thd, val, spv->default_value)))
5037     return true;
5038 
5039   sp_instr_set *sp_set= new (thd->mem_root)
5040                         sp_instr_set(instructions(), spcont, rh,
5041                                      spv->offset, val, lex,
5042                                      responsible_to_free_lex);
5043 
5044   return sp_set == NULL || add_instr(sp_set);
5045 }
5046 
5047 
5048 /**
5049   Similar to set_local_variable(), but for ROW variable fields.
5050 */
5051 
5052 bool
5053 sp_head::set_local_variable_row_field(THD *thd, sp_pcontext *spcont,
5054                                       const Sp_rcontext_handler *rh,
5055                                       sp_variable *spv, uint field_idx,
5056                                       Item *val, LEX *lex)
5057 {
5058   if (!(val= adjust_assignment_source(thd, val, NULL)))
5059     return true;
5060 
5061   sp_instr_set_row_field *sp_set= new (thd->mem_root)
5062                                   sp_instr_set_row_field(instructions(),
5063                                                          spcont, rh,
5064                                                          spv->offset,
5065                                                          field_idx, val,
5066                                                          lex, true);
5067   return sp_set == NULL || add_instr(sp_set);
5068 }
5069 
5070 
5071 bool
5072 sp_head::set_local_variable_row_field_by_name(THD *thd, sp_pcontext *spcont,
5073                                               const Sp_rcontext_handler *rh,
5074                                               sp_variable *spv,
5075                                               const LEX_CSTRING *field_name,
5076                                               Item *val, LEX *lex)
5077 {
5078   if (!(val= adjust_assignment_source(thd, val, NULL)))
5079     return true;
5080 
5081   sp_instr_set_row_field_by_name *sp_set=
5082     new (thd->mem_root) sp_instr_set_row_field_by_name(instructions(),
5083                                                        spcont, rh,
5084                                                        spv->offset,
5085                                                        *field_name,
5086                                                        val,
5087                                                        lex, true);
5088   return sp_set == NULL || add_instr(sp_set);
5089 }
5090 
5091 
5092 bool sp_head::add_open_cursor(THD *thd, sp_pcontext *spcont, uint offset,
5093                               sp_pcontext *param_spcont,
5094                               List<sp_assignment_lex> *parameters)
5095 {
5096   /*
5097     The caller must make sure that the number of formal parameters matches
5098     the number of actual parameters.
5099   */
5100   DBUG_ASSERT((param_spcont ? param_spcont->context_var_count() :  0) ==
5101               (parameters ? parameters->elements : 0));
5102 
5103   if (parameters &&
5104       add_set_cursor_param_variables(thd, param_spcont, parameters))
5105     return true;
5106 
5107   sp_instr_copen *i= new (thd->mem_root)
5108                      sp_instr_copen(instructions(), spcont, offset);
5109   return i == NULL || add_instr(i);
5110 }
5111 
5112 
5113 bool sp_head::add_for_loop_open_cursor(THD *thd, sp_pcontext *spcont,
5114                                        sp_variable *index,
5115                                        const sp_pcursor *pcursor, uint coffset,
5116                                        sp_assignment_lex *param_lex,
5117                                        Item_args *parameters)
5118 {
5119   if (parameters &&
5120       add_set_for_loop_cursor_param_variables(thd, pcursor->param_context(),
5121                                               param_lex, parameters))
5122     return true;
5123 
5124   sp_instr *instr_copy_struct=
5125     new (thd->mem_root) sp_instr_cursor_copy_struct(instructions(),
5126                                                     spcont, coffset,
5127                                                     pcursor->lex(),
5128                                                     index->offset);
5129   if (instr_copy_struct == NULL || add_instr(instr_copy_struct))
5130     return true;
5131 
5132   sp_instr_copen *instr_copen=
5133     new (thd->mem_root) sp_instr_copen(instructions(), spcont, coffset);
5134   if (instr_copen == NULL || add_instr(instr_copen))
5135     return true;
5136 
5137   sp_instr_cfetch *instr_cfetch=
5138     new (thd->mem_root) sp_instr_cfetch(instructions(),
5139                                         spcont, coffset, false);
5140   if (instr_cfetch == NULL || add_instr(instr_cfetch))
5141     return true;
5142   instr_cfetch->add_to_varlist(index);
5143   return false;
5144 }
5145 
5146 
5147 bool
5148 sp_head::add_set_for_loop_cursor_param_variables(THD *thd,
5149                                                  sp_pcontext *param_spcont,
5150                                                  sp_assignment_lex *param_lex,
5151                                                  Item_args *parameters)
5152 {
5153   DBUG_ASSERT(param_spcont->context_var_count() == parameters->argument_count());
5154   for (uint idx= 0; idx < parameters->argument_count(); idx ++)
5155   {
5156     /*
5157       param_lex is shared between multiple items (cursor parameters).
5158       Only the last sp_instr_set is responsible for freeing param_lex.
5159       See more comments in LEX::sp_for_loop_cursor_declarations in sql_lex.cc.
5160     */
5161     bool last= idx + 1 == parameters->argument_count();
5162     sp_variable *spvar= param_spcont->get_context_variable(idx);
5163     if (set_local_variable(thd, param_spcont,
5164                            &sp_rcontext_handler_local,
5165                            spvar, parameters->arguments()[idx],
5166                            param_lex, last))
5167       return true;
5168   }
5169   return false;
5170 }
5171 
5172 
5173 bool sp_head::spvar_fill_row(THD *thd,
5174                              sp_variable *spvar,
5175                              Row_definition_list *defs)
5176 {
5177   spvar->field_def.set_row_field_definitions(defs);
5178   spvar->field_def.field_name= spvar->name;
5179   if (fill_spvar_definition(thd, &spvar->field_def))
5180     return true;
5181   row_fill_field_definitions(thd, defs);
5182   return false;
5183 }
5184 
5185 
5186 bool sp_head::spvar_fill_type_reference(THD *thd,
5187                                         sp_variable *spvar,
5188                                         const LEX_CSTRING &table,
5189                                         const LEX_CSTRING &col)
5190 {
5191   Qualified_column_ident *ref;
5192   if (!(ref= new (thd->mem_root) Qualified_column_ident(&table, &col)))
5193     return true;
5194   fill_spvar_using_type_reference(spvar, ref);
5195   return false;
5196 }
5197 
5198 
5199 bool sp_head::spvar_fill_type_reference(THD *thd,
5200                                         sp_variable *spvar,
5201                                         const LEX_CSTRING &db,
5202                                         const LEX_CSTRING &table,
5203                                         const LEX_CSTRING &col)
5204 {
5205   Qualified_column_ident *ref;
5206   if (!(ref= new (thd->mem_root) Qualified_column_ident(thd, &db, &table, &col)))
5207     return true;
5208   fill_spvar_using_type_reference(spvar, ref);
5209   return false;
5210 }
5211 
5212 
5213 bool sp_head::spvar_fill_table_rowtype_reference(THD *thd,
5214                                                  sp_variable *spvar,
5215                                                  const LEX_CSTRING &table)
5216 {
5217   Table_ident *ref;
5218   if (!(ref= new (thd->mem_root) Table_ident(&table)))
5219     return true;
5220   fill_spvar_using_table_rowtype_reference(thd, spvar, ref);
5221   return false;
5222 }
5223 
5224 
5225 bool sp_head::spvar_fill_table_rowtype_reference(THD *thd,
5226                                                  sp_variable *spvar,
5227                                                  const LEX_CSTRING &db,
5228                                                  const LEX_CSTRING &table)
5229 {
5230   Table_ident *ref;
5231   if (!(ref= new (thd->mem_root) Table_ident(thd, &db, &table, false)))
5232     return true;
5233   fill_spvar_using_table_rowtype_reference(thd, spvar, ref);
5234   return false;
5235 }
5236 
5237 
5238 /*
5239   In Oracle mode stored routines have an optional name
5240   at the end of a declaration:
5241     PROCEDURE p1 AS
5242     BEGIN
5243       NULL
5244     END p1;
5245   Check that the first p1 and the last p1 match.
5246 */
5247 
5248 bool sp_head::check_package_routine_end_name(const LEX_CSTRING &end_name) const
5249 {
5250   LEX_CSTRING non_qualified_name= m_name;
5251   const char *errpos;
5252   size_t ofs;
5253   if (!end_name.length)
5254     return false; // No end name
5255   if (!(errpos= strrchr(m_name.str, '.')))
5256   {
5257     errpos= m_name.str;
5258     goto err;
5259   }
5260   errpos++;
5261   ofs= errpos - m_name.str;
5262   non_qualified_name.str+= ofs;
5263   non_qualified_name.length-= ofs;
5264   if (Sp_handler::eq_routine_name(end_name, non_qualified_name))
5265     return false;
5266 err:
5267   my_error(ER_END_IDENTIFIER_DOES_NOT_MATCH, MYF(0), end_name.str, errpos);
5268   return true;
5269 }
5270 
5271 
5272 ulong sp_head::sp_cache_version() const
5273 {
5274   return m_parent ? m_parent->sp_cache_version() : m_sp_cache_version;
5275 }
5276