forked from FirebirdSQL/php-firebird
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfbird_query_exec.c
More file actions
executable file
·2076 lines (1811 loc) · 71.8 KB
/
Copy pathfbird_query_exec.c
File metadata and controls
executable file
·2076 lines (1811 loc) · 71.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: PHP-3.01
* SPDX-FileCopyrightText: The PHP Group and contributors (see CREDITS) */
/* Enable GNU features (includes X/Open for strptime, BSD for strlcpy/tm_zone) */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <string.h>
#include "php.h"
#include "php_ini.h"
#if HAVE_FIREBIRD
#include "ext/standard/php_standard.h"
#include "php_firebird.h"
#include "php_fbird_includes.h"
#include "php_fbird_query_internal.h"
#include "php_fbird_query_prepare.h"
#include "php_fbird_query_bind.h"
#include "php_fbird_query_array.h"
#include "firebird_utils.h"
#include "fbird_classes.h"
#include "src/php_fbird_compat.h"
/* le_query is defined in fbird_query_prepare.c */
/* Helper: fetch fbird_transaction* and optional zend_resource* from either a
* le_trans resource zval or a Firebird\Transaction object zval.
* Sets *res_out (if non-NULL) to the underlying zend_resource*.
* Returns NULL if z does not hold a valid le_trans. */
static fbird_transaction *_php_fbird_trans_from_zval(zval *z, zend_resource **res_out)
{
if (!z) return NULL;
if (Z_TYPE_P(z) == IS_RESOURCE) {
fbird_transaction *t = (fbird_transaction *)zend_fetch_resource_ex(z, NULL, le_trans);
if (t && res_out) *res_out = Z_RES_P(z);
return t;
}
/* Only treat as Transaction object if it actually IS a Firebird\Transaction.
* Without this check, a Firebird\Connection object would be misinterpreted
* causing wrong memory access via fbird_transaction_get_resource(). */
if (Z_TYPE_P(z) == IS_OBJECT &&
instanceof_function(Z_OBJCE_P(z), fbird_transaction_ce)) {
zend_resource *res = fbird_transaction_get_resource(Z_OBJ_P(z));
if (res) {
fbird_transaction *t = (fbird_transaction *)zend_fetch_resource(res, "Firebird transaction", le_trans);
if (t && res_out) *res_out = res;
return t;
}
}
return NULL;
}
/* Helper: fetch fbird_db_link* from either a le_link/le_plink resource zval
* or a Firebird\Connection object zval.
* Returns NULL if z does not hold a valid connection.
* Uses instanceof_function guard to prevent misinterpreting Transaction objects. */
static fbird_db_link *_php_fbird_link_from_zval(zval *z)
{
if (!z) return NULL;
ZVAL_DEREF(z);
if (Z_TYPE_P(z) == IS_RESOURCE) {
fbird_db_link *link = (fbird_db_link *)zend_fetch_resource_ex(z, NULL, le_link);
if (!link) link = (fbird_db_link *)zend_fetch_resource_ex(z, NULL, le_plink);
return link;
}
/* Only treat as Connection object if it actually IS a Firebird\Connection.
* Without this guard, a Firebird\Transaction object could be misinterpreted. */
if (Z_TYPE_P(z) == IS_OBJECT &&
instanceof_function(Z_OBJCE_P(z), fbird_connection_ce)) {
zend_resource *conn_res = fbird_connection_get_resource(Z_OBJ_P(z));
if (conn_res) {
return (fbird_db_link *)zend_fetch_resource2(conn_res, LE_LINK, le_link, le_plink);
}
}
return NULL;
}
int _php_fbird_exec(INTERNAL_FUNCTION_PARAMETERS, fbird_query *fb_query, zval *args, int bind_n)
{
ISC_STATUS status[256];
int rv = FAILURE;
ISC_STATUS isc_result;
int argc = fb_query->in_fields_count;
(void)execute_data;
RESET_ERRMSG;
RETVAL_FALSE;
/* Enhanced parameter validation BEFORE Firebird API calls.
*
* Validation behavior:
* - bind_n < 0 or argc < 0: Invalid state → E_WARNING + FAILURE
* - bind_n < argc (too few args given): E_WARNING + FAILURE (execution blocked)
* - bind_n > argc (extra args given): E_NOTICE (execution continues, extra args ignored)
*
* This stricter validation provides clearer error messages compared to letting
* Firebird return cryptic errors for parameter mismatches.
*
* Test coverage: tests/bug45373.phpt
* Documentation: docs/development/FBIRD_QUERY_EXEC_FIXES.md
*/
if (bind_n < 0 || argc < 0) {
_php_fbird_module_error("Invalid parameter count: bind_n=%d, argc=%d", bind_n, argc);
return FAILURE;
}
if (bind_n != argc) {
if (bind_n < argc) {
/* Too few args: error, cannot proceed */
_php_fbird_module_error(
"Statement expects %d arguments, %d given", argc, bind_n);
return FAILURE;
} else {
/* Extra args: notice, execution continues (backward compatible) */
php_error_docref(NULL, E_NOTICE,
"Statement expects %d arguments, %d given", argc, bind_n);
}
}
/* Cursor lifecycle management: before any re-execution, close an open cursor
* unconditionally to match legacy semantics and avoid -502 reopen errors. */
if (fb_query->statement_type != isc_info_sql_stmt_exec_procedure && fb_query->is_open) {
FBDEBUG("Closing open cursor before re-execution");
/* Be tolerant: silently ignore ALL errors when attempting to close the cursor
* before re-execution. The cursor may already have been closed by various means
* (fbird_free_result, transaction commit, EOF reached, etc.) - this is expected
* and should not generate warnings. We unconditionally reset the is_open flag. */
/* OO API Only: Close cursor via fbs_close_cursor() */
if (fb_query->fbs_statement) {
fbs_close_cursor(fb_query->fbs_statement, status);
}
fb_query->is_open = 0;
fb_query->has_more_rows = 0;
}
/* NOTE: We intentionally do NOT use SEPARATE_ZVAL here.
*
* Previously, SEPARATE_ZVAL was called on each argument to create independent
* copies before binding. However, this caused memory corruption issues where
* the PHP caller's original array variables would be corrupted after fbird_query
* returned.
*
* The root cause was that SEPARATE_ZVAL's interaction with PHP 8's copy-on-write
* semantics and the parameter passing mechanism corrupted the original zval's
* HashTable.
*
* The fix is to NOT separate the zvals. Instead, _php_fbird_bind_array() now
* uses zval_get_long(), zval_get_double(), zval_get_string() which create
* temporary copies of values without modifying the original zval in-place.
* This preserves the caller's arrays while still allowing Firebird binding.
*/
switch (fb_query->statement_type) {
fbird_tr_list **l;
fbird_transaction *trans;
case isc_info_sql_stmt_start_trans:
/* OO API path: Use fbt_start() for OO API connections.
* This avoids calling isc_dsql_execute_immediate() with invalid legacy handles.
* Note: SET TRANSACTION SQL parameters are not parsed here - uses default TPB. */
if (fb_query->link && fb_query->link->fbc_connection) {
void *attachment = fbc_get_attachment(fb_query->link->fbc_connection);
void *new_trans = NULL;
FBDEBUG("OO API: Executing SET TRANSACTION via fbt_start()");
/* Start transaction with default TPB (READ_WRITE, WAIT, CONCURRENCY) */
new_trans = fbt_start(FBG(master_instance), attachment, 0, NULL, status);
if (!new_trans) {
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
trans = (fbird_transaction *) emalloc(sizeof(fbird_transaction));
trans->link_cnt = 1;
trans->affected_rows = 0;
trans->fbt_transaction = new_trans;
trans->db_link[0] = fb_query->link;
/* Sentinel head node: reserves index 0 for the default transaction.
* _php_fbird_commit_link() uses i==0 to distinguish:
* - Default tx (index 0): commit + efree (not a registered resource)
* - Explicit tx (index >0): rollback + leave to le_trans destructor
* Do NOT remove this placeholder — see issue #541 investigation. */
if (fb_query->link->tr_list == NULL) {
fb_query->link->tr_list = (fbird_tr_list *) emalloc(sizeof(fbird_tr_list));
fb_query->link->tr_list->trans = NULL;
fb_query->link->tr_list->next = NULL;
}
/* link the transaction into the connection-transaction list */
for (l = &fb_query->link->tr_list; *l != NULL; l = &(*l)->next);
*l = (fbird_tr_list *) emalloc(sizeof(fbird_tr_list));
(*l)->trans = trans;
(*l)->next = NULL;
RETVAL_RES(zend_register_resource(trans, le_trans));
Z_TRY_ADDREF_P(return_value);
return SUCCESS;
}
/* OO API Only: Connection must have OO API handle for SET TRANSACTION */
_php_fbird_module_error("SET TRANSACTION requires OO API connection (fbc_connection required)");
goto _php_fbird_ex_error;
case isc_info_sql_stmt_commit:
case isc_info_sql_stmt_rollback:
/* OO API path: Use fbt_commit()/fbt_rollback() for OO API transactions.
* This avoids calling isc_dsql_execute_immediate() with invalid legacy handles.
*
* IMPORTANT: fbt_commit/fbt_rollback return 0 on success, non-zero on error.
*/
if (fb_query->trans && fb_query->trans->fbt_transaction) {
int rc;
if (fb_query->statement_type == isc_info_sql_stmt_commit) {
FBDEBUG("OO API: Executing COMMIT via fbt_commit()");
rc = fbt_commit(fb_query->trans->fbt_transaction, status);
} else {
FBDEBUG("OO API: Executing ROLLBACK via fbt_rollback()");
rc = fbt_rollback(fb_query->trans->fbt_transaction, status);
}
if (rc != 0) {
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
/* Mark transaction as closed.
* Note: Do NOT delete the PHP resource here.
* Legacy behavior keeps the resource alive but invalid for further use.
*/
fb_query->trans->fbt_transaction = NULL;
RETVAL_TRUE;
return SUCCESS;
}
/* OO API Only: Transaction must have OO API handle for COMMIT/ROLLBACK */
_php_fbird_module_error("COMMIT/ROLLBACK requires OO API transaction (fbt_transaction required)");
goto _php_fbird_ex_error;
default:
RETVAL_FALSE;
}
if (fb_query->in_fields_count) { /* has placeholders */
FBDEBUG("Query wants XSQLDA for input");
if (_php_fbird_bind(fb_query, args) == FAILURE) {
FBDEBUG("Could not bind input XSQLDA");
goto _php_fbird_ex_error;
}
/* Verify OO API message buffer infrastructure is available.
* If in_metadata or in_msg_buffer is not set, OO API execution
* with parameters is not possible - report clear error. */
if (!fb_query->in_metadata) {
_php_fbird_module_error("OO API input metadata not available for parameterized query");
goto _php_fbird_ex_error;
}
if (!fb_query->in_msg_buffer) {
_php_fbird_module_error("OO API input message buffer not allocated for parameterized query");
goto _php_fbird_ex_error;
}
/* Transfer bound XSQLDA values to OO API message buffer.
* This is required because the OO API uses flat message buffers
* with offsets from IMessageMetadata, not XSQLDA structures. */
if (_php_fbird_xsqlda_to_msg_buffer(fb_query) == FAILURE) {
FBDEBUG("Could not transfer XSQLDA to message buffer");
goto _php_fbird_ex_error;
}
}
isc_result = 0;
/* Issue #294: If the default transaction was committed by autocommit
* (fbt_transaction is NULL), restart it before executing. This allows
* fbird_execute() on prepared statements created with the default tx
* to work after a fbird_query() DML call committed the default tx.
* trans_res == NULL ensures we only restart the default (implicit) tx,
* not an explicit user-started transaction. */
if (fb_query->trans && fb_query->trans->fbt_transaction == NULL &&
fb_query->trans_res == NULL &&
fb_query->link && fb_query->link->fbc_connection) {
fb_query->trans = NULL; /* force _php_fbird_def_trans to restart */
if (SUCCESS != _php_fbird_def_trans(fb_query->link, &fb_query->trans)) {
return FAILURE; /* _php_fbird_def_trans already reported the error */
}
}
if (fb_query->fbs_statement && fb_query->trans && fb_query->trans->fbt_transaction) {
void *transaction_ptr = fbt_get_handle(fb_query->trans->fbt_transaction);
int oo_api_success = 0;
if (transaction_ptr) {
/* For SELECT statements, open cursor using OO API */
if (fb_query->statement_type == isc_info_sql_stmt_select ||
fb_query->statement_type == isc_info_sql_stmt_select_for_upd) {
/*
* OO API cursor open for SELECT.
* Uses IMessageMetadata for parameter binding (Firebird 3.0+ OO API).
* Input parameters are passed via in_msg_buffer/in_metadata.
*/
oo_api_success = fbs_open_cursor(
FBG(master_instance),
fb_query->fbs_statement,
transaction_ptr,
fb_query->in_msg_buffer, /* in_msg: parameter values */
fb_query->in_metadata, /* in_metadata: parameter metadata */
0, /* cursor_flags: default */
status
);
if (oo_api_success) {
FBDEBUG("OO API fbs_open_cursor() succeeded for SELECT");
isc_result = 0; /* Success */
} else {
/* OO API cursor open failed - report error immediately, no fallback */
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
}
/* For non-SELECT (INSERT/UPDATE/DELETE) without RETURNING, use fbs_execute */
else if ((fb_query->statement_type == isc_info_sql_stmt_insert ||
fb_query->statement_type == isc_info_sql_stmt_update ||
fb_query->statement_type == isc_info_sql_stmt_delete) &&
!fb_query->out_sqlda) {
/*
* OO API execute for DML (no RETURNING).
* Uses IMessageMetadata for parameter binding (Firebird 3.0+ OO API).
* Input parameters are passed via in_msg_buffer/in_metadata.
*/
oo_api_success = fbs_execute(
FBG(master_instance),
fb_query->fbs_statement,
transaction_ptr,
fb_query->in_msg_buffer, /* in_msg: parameter values */
fb_query->in_metadata, /* in_metadata: parameter metadata */
NULL, /* out_msg: no output for DML without RETURNING */
NULL, /* out_metadata: no output for DML without RETURNING */
status
);
if (oo_api_success) {
FBDEBUG("OO API fbs_execute() succeeded for DML");
isc_result = 0; /* Success */
} else {
/* OO API execution failed - report error immediately, no fallback */
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
}
/* For DDL statements (CREATE, DROP, ALTER, etc.), use fbs_execute */
else if (fb_query->statement_type == isc_info_sql_stmt_ddl) {
/*
* DDL statements have no input/output parameters.
* Execute directly via OO API.
*/
oo_api_success = fbs_execute(
FBG(master_instance),
fb_query->fbs_statement,
transaction_ptr,
NULL, /* in_msg */
NULL, /* in_metadata */
NULL, /* out_msg */
NULL, /* out_metadata */
status
);
if (oo_api_success) {
FBDEBUG("OO API fbs_execute() succeeded for DDL");
isc_result = 0; /* Success */
} else {
/* OO API execution failed - report error immediately, no fallback */
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
}
/* SAVEPOINT statements (SAVEPOINT / ROLLBACK TO SAVEPOINT / RELEASE SAVEPOINT)
* are reported as statement type 14. They have no input/output parameters.
*/
else if (fb_query->statement_type == isc_info_sql_stmt_savepoint) {
oo_api_success = fbs_execute(
FBG(master_instance),
fb_query->fbs_statement,
transaction_ptr,
NULL,
NULL,
NULL,
NULL,
status
);
if (oo_api_success) {
FBDEBUG("OO API fbs_execute() succeeded for SAVEPOINT");
isc_result = 0;
} else {
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
}
/* For EXECUTE PROCEDURE - use fbs_execute with input and output buffers */
else if (fb_query->statement_type == isc_info_sql_stmt_exec_procedure) {
/*
* OO API execute for EXECUTE PROCEDURE.
* Uses IMessageMetadata for parameter binding (Firebird 3.0+ OO API).
* Input parameters are passed via in_msg_buffer/in_metadata.
* Output parameters are returned via out_msg_buffer/out_metadata.
*/
oo_api_success = fbs_execute(
FBG(master_instance),
fb_query->fbs_statement,
transaction_ptr,
fb_query->in_msg_buffer, /* in_msg: input parameter values */
fb_query->in_metadata, /* in_metadata: input parameter metadata */
fb_query->out_msg_buffer, /* out_msg: output parameter values */
fb_query->out_metadata, /* out_metadata: output parameter metadata */
status
);
if (oo_api_success) {
FBDEBUG("OO API fbs_execute() succeeded for EXECUTE PROCEDURE");
isc_result = 0; /* Success */
} else {
/* OO API execution failed - report error immediately, no fallback */
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
}
/* For DML with RETURNING - open cursor, fetch 1 row into out_msg_buffer, close cursor */
else if ((fb_query->statement_type == isc_info_sql_stmt_insert ||
fb_query->statement_type == isc_info_sql_stmt_update ||
fb_query->statement_type == isc_info_sql_stmt_delete) &&
fb_query->out_sqlda) {
/*
* OO API handling for DML with RETURNING clause.
*
* This behaves like legacy isc_dsql_execute2():
* - execute statement
* - copy one result row into out_msg_buffer
* - close cursor immediately
*
* RETURNING typically yields exactly one row.
*/
oo_api_success = fbs_open_cursor(
FBG(master_instance),
fb_query->fbs_statement,
transaction_ptr,
fb_query->in_msg_buffer,
fb_query->in_metadata,
0,
status
);
if (!oo_api_success) {
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
int fetch_result = fbs_fetch(
FBG(master_instance),
fb_query->fbs_statement,
fb_query->out_msg_buffer,
status
);
if (fetch_result == -1) {
_php_fbird_error(status);
fbs_close_cursor(fb_query->fbs_statement, status);
goto _php_fbird_ex_error;
}
/* Always close cursor for DML RETURNING (like execute2) */
fbs_close_cursor(fb_query->fbs_statement, status);
/* fetch_result: 1=row copied into out_msg_buffer, 0=no data */
if (fetch_result == 1) {
fb_query->was_result_once = 1;
}
isc_result = 0;
}
/* Unhandled statement type for OO API */
else {
_php_fbird_module_error("Statement type %d not supported via OO API",
fb_query->statement_type);
goto _php_fbird_ex_error;
}
}
/* If OO API succeeded, skip to done */
if (oo_api_success) {
goto execute_done;
}
/* Should not reach here - all paths either succeed or error out above */
_php_fbird_module_error("OO API execution path did not complete");
goto _php_fbird_ex_error;
}
/*
* Non-OO API path: This connection does not have OO API transaction.
* This should only happen for legacy connections (without fbt_transaction).
* For now, report an error as we're removing legacy API support.
*/
_php_fbird_module_error("Legacy API execution not supported. Connection must use OO API (fbt_transaction required)");
goto _php_fbird_ex_error;
execute_done:
if (isc_result) {
FBDEBUG("Could not execute query");
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
fb_query->trans->affected_rows = 0;
/* For SELECT statements, mark cursor state as open with rows pending.
* Check both legacy (out_sqlda) and OO API (fbs_statement) paths. */
if ((fb_query->statement_type == isc_info_sql_stmt_select ||
fb_query->statement_type == isc_info_sql_stmt_select_for_upd) &&
(fb_query->out_sqlda || fb_query->fbs_statement)) {
fb_query->is_open = 1;
fb_query->has_more_rows = 1;
/* OO API SELECT path: return the query resource directly when no SQLDA.
* The cursor is open via fbs_open_cursor() and fetching will use fbs_fetch(). */
if (fb_query->fbs_statement && !fb_query->out_sqlda) {
RETVAL_RES(fb_query->res);
Z_TRY_ADDREF_P(return_value);
rv = SUCCESS;
return rv;
}
}
/* Handle result sets for SELECT, EXECUTE PROCEDURE, and DML with RETURNING clauses */
if (fb_query->out_sqlda) { /* output variables in select, select for update, or RETURNING */
/* For EXECUTE PROCEDURE and INSERT/UPDATE/DELETE...RETURNING, create independent result resources to avoid
* shared state issues where each execution overwrites the previous result.
*/
if (fb_query->statement_type == isc_info_sql_stmt_exec_procedure ||
fb_query->statement_type == isc_info_sql_stmt_insert ||
fb_query->statement_type == isc_info_sql_stmt_update ||
fb_query->statement_type == isc_info_sql_stmt_delete) {
/* Create a new query structure for this specific result */
fbird_query *result_query = ecalloc(1, sizeof(fbird_query));
/* Initialize error cleanup flag */
int cleanup_needed = 1;
/* Copy essential fields from the original query */
result_query->link = fb_query->link;
result_query->trans = fb_query->trans;
result_query->trans_res = fb_query->trans_res;
result_query->dialect = fb_query->dialect;
result_query->statement_type = fb_query->statement_type;
result_query->out_fields_count = fb_query->out_fields_count;
/* OO API snapshot support (EXECUTE PROCEDURE + DML RETURNING)
*
* The OO API writes result values into a flat message buffer.
* For one-shot results, we must snapshot that buffer into the
* returned result resource so subsequent executions don't
* overwrite it.
*/
result_query->fbs_statement = fb_query->fbs_statement;
result_query->out_metadata = fb_query->out_metadata;
result_query->out_msg_length = fb_query->out_msg_length;
result_query->out_msg_buffer = NULL;
if (fb_query->out_msg_buffer && fb_query->out_msg_length > 0) {
result_query->out_msg_buffer = safe_emalloc(1, fb_query->out_msg_length, 0);
memcpy(result_query->out_msg_buffer, fb_query->out_msg_buffer, fb_query->out_msg_length);
}
/* Flag used by fbird_fetch_*() to detect buffered RETURNING rows.
* For EXECUTE PROCEDURE it is ignored, but keep it consistent. */
result_query->was_result_once = fb_query->was_result_once;
/* Reuse the OO statement wrapper for metadata operations. */
result_query->fbs_statement = fb_query->fbs_statement;
/* Keep a copy of SQL text for symmetry with SELECT path and
* potential debug/logging uses in helper routines. */
if (fb_query->query) {
result_query->query = estrdup(fb_query->query);
}
/* Validate source SQLDA before processing */
if (fb_query->out_sqlda && fb_query->out_fields_count > 0) {
/* Validate SQLDA structure integrity */
if (fb_query->out_sqlda->sqln != fb_query->out_fields_count ||
fb_query->out_sqlda->sqld != fb_query->out_fields_count) {
_php_fbird_module_error("EXECUTE PROCEDURE: Invalid SQLDA structure - sqln=%d, sqld=%d, expected=%d",
fb_query->out_sqlda->sqln, fb_query->out_sqlda->sqld, fb_query->out_fields_count);
goto cleanup_result_query;
}
/* Allocate SQLDA structure with bounds checking */
size_t sqlda_size = XSQLDA_LENGTH(fb_query->out_fields_count);
if (sqlda_size < sizeof(XSQLDA) || fb_query->out_fields_count > 32767) {
_php_fbird_module_error("EXECUTE PROCEDURE: Invalid field count %d for SQLDA allocation",
fb_query->out_fields_count);
goto cleanup_result_query;
}
result_query->out_sqlda = (XSQLDA *) emalloc(sqlda_size);
if (!result_query->out_sqlda) {
_php_fbird_module_error("EXECUTE PROCEDURE: Failed to allocate SQLDA memory");
goto cleanup_result_query;
}
/* Safe copy of SQLDA header and variable array */
memcpy(result_query->out_sqlda, fb_query->out_sqlda, sqlda_size);
/* CRITICAL SAFETY FIX: Clear all sqldata pointers in the copy immediately. */
for (int i = 0; i < fb_query->out_fields_count; i++) {
result_query->out_sqlda->sqlvar[i].sqldata = NULL;
}
/* Allocate null indicator array with validation */
result_query->out_nullind = safe_emalloc(sizeof(*result_query->out_nullind),
fb_query->out_fields_count, 0);
if (!result_query->out_nullind) {
_php_fbird_module_error("EXECUTE PROCEDURE: Failed to allocate null indicator array");
goto cleanup_result_query;
}
/* Safe copy of null indicators */
memcpy(result_query->out_nullind, fb_query->out_nullind,
sizeof(*result_query->out_nullind) * fb_query->out_fields_count);
/* Deep copy data for each field using safer copying mechanism */
for (int i = 0; i < fb_query->out_fields_count; i++) {
XSQLVAR *orig_var = &fb_query->out_sqlda->sqlvar[i];
XSQLVAR *result_var = &result_query->out_sqlda->sqlvar[i];
/* Reset sqldata pointer - will be set by safe copy function */
result_var->sqldata = NULL;
/* Use safer copying function with comprehensive validation */
if (FAILURE == _php_fbird_safe_copy_sqlvar_data(result_var, orig_var, i, fb_query->query)) {
goto cleanup_result_query;
}
}
/* Update sqlind pointers to point to the new null indicators */
for (int i = 0; i < fb_query->out_fields_count; i++) {
if (result_query->out_sqlda->sqlvar[i].sqltype & 1) {
result_query->out_sqlda->sqlvar[i].sqlind = &result_query->out_nullind[i];
} else {
result_query->out_sqlda->sqlvar[i].sqlind = NULL;
}
}
}
/* Copy input parameter metadata so fbird_num_params()/fbird_param_info()
* work on the returned result resource (e.g., fbird_query() path). */
result_query->in_fields_count = fb_query->in_fields_count;
if (fb_query->in_fields_count > 0 && fb_query->in_sqlda) {
size_t in_size = XSQLDA_LENGTH(fb_query->in_fields_count);
result_query->in_sqlda = (XSQLDA *) emalloc(in_size);
memcpy(result_query->in_sqlda, fb_query->in_sqlda, in_size);
/* Ensure indicators are not dangling for inputs on the cloned structure */
for (int i = 0; i < result_query->in_sqlda->sqld; i++) {
result_query->in_sqlda->sqlvar[i].sqlind = NULL;
result_query->in_sqlda->sqlvar[i].sqlind = NULL;
}
}
/* Set result flags - EXECUTE PROCEDURE results are immediately available */
result_query->has_more_rows = 1; /* Data is available for fetching */
result_query->is_open = 1; /* Result can be fetched once */
/* Register the result as a new resource - this transfers ownership
* IMPORTANT: This result does NOT own the statement handle. */
result_query->owns_stmt_handle = 0;
result_query->res = zend_register_resource(result_query, le_query);
if (!result_query->res) {
_php_fbird_module_error("EXECUTE PROCEDURE: Failed to register result resource");
goto cleanup_result_query;
}
/* Independent result snapshot: DO NOT link as child of parent query. */
result_query->parent = NULL;
/* Eagerly load column aliases before clearing the statement handle. */
if (_php_fbird_alloc_ht_aliases(result_query) == FAILURE) {
_php_fbird_module_error("EXECUTE PROCEDURE: Failed to allocate aliases");
goto cleanup_result_query;
}
result_query->fbs_statement = NULL; /* Do not reference the handle as it may be freed */
/* Success - disable cleanup since resource system now owns the memory */
cleanup_needed = 0;
RETVAL_RES(result_query->res);
Z_TRY_ADDREF_P(return_value);
return SUCCESS;
cleanup_result_query:
/* Clean up partially allocated result_query on error path */
if (cleanup_needed && result_query) {
/* Free field data if partially allocated */
if (result_query->out_sqlda && result_query->out_fields_count > 0) {
for (int i = 0; i < result_query->out_fields_count; i++) {
if (result_query->out_sqlda->sqlvar[i].sqldata) {
efree(result_query->out_sqlda->sqlvar[i].sqldata);
}
}
}
/* Free SQLDA structure */
if (result_query->out_sqlda) {
efree(result_query->out_sqlda);
}
/* Free null indicator array */
if (result_query->out_nullind) {
efree(result_query->out_nullind);
}
/* Free alias hash table if allocated */
if (result_query->ht_aliases) {
zend_array_destroy(result_query->ht_aliases);
}
/* Free the result query structure itself */
efree(result_query);
}
/* Propagate error to caller */
goto _php_fbird_ex_error;
} else {
/* SELECT queries: Create independent result data to prevent use-after-free vulnerability */
/* Create a new query structure for this specific result */
fbird_query *result_query = ecalloc(1, sizeof(fbird_query));
/* Initialize error cleanup flag */
int cleanup_needed = 1;
/* Copy essential fields from the original query */
result_query->link = fb_query->link;
result_query->trans = fb_query->trans;
result_query->trans_res = fb_query->trans_res;
result_query->dialect = fb_query->dialect;
result_query->statement_type = fb_query->statement_type;
result_query->out_fields_count = fb_query->out_fields_count;
result_query->was_result_once = 1;
/* Reuse parent's prepared statement and already-open cursor */
result_query->query = estrdup(fb_query->query);
/* Copy OO API structures for fetch operations
*
* IMPORTANT: Snapshot the message buffer.
* The parent query owns and frees fb_query->out_msg_buffer.
* Child SELECT results must have their own copy to avoid double-free / UAF
* when both parent and child resources are destroyed.
*/
result_query->fbs_statement = fb_query->fbs_statement;
result_query->out_metadata = fb_query->out_metadata;
result_query->out_msg_length = fb_query->out_msg_length;
result_query->out_msg_buffer = NULL;
if (fb_query->out_msg_buffer && fb_query->out_msg_length > 0) {
result_query->out_msg_buffer = safe_emalloc(1, fb_query->out_msg_length, 0);
memcpy(result_query->out_msg_buffer, fb_query->out_msg_buffer, fb_query->out_msg_length);
}
/* Copy input parameter metadata so fbird_num_params()/fbird_param_info()
* work on the returned result resource (e.g., fbird_query() path). */
result_query->in_fields_count = fb_query->in_fields_count;
if (fb_query->in_fields_count > 0 && fb_query->in_sqlda) {
size_t in_size = XSQLDA_LENGTH(fb_query->in_fields_count);
result_query->in_sqlda = (XSQLDA *) emalloc(in_size);
memcpy(result_query->in_sqlda, fb_query->in_sqlda, in_size);
/* Input buffer pointers are not needed on the result copy when
* reusing the same open cursor; keep them NULL to avoid misuse. */
for (int i = 0; i < result_query->in_sqlda->sqld; i++) {
result_query->in_sqlda->sqlvar[i].sqlind = NULL;
result_query->in_sqlda->sqlvar[i].sqldata = NULL;
}
}
/* Create independent copies of result data structures */
if (fb_query->out_fields_count > 0 && fb_query->out_sqlda) {
/* Validate source SQLDA before processing */
if (fb_query->out_sqlda->sqln != fb_query->out_fields_count ||
fb_query->out_sqlda->sqld != fb_query->out_fields_count) {
_php_fbird_module_error("SELECT: Invalid SQLDA structure - sqln=%d, sqld=%d, expected=%d",
fb_query->out_sqlda->sqln, fb_query->out_sqlda->sqld, fb_query->out_fields_count);
goto cleanup_select_result_query;
}
/* Allocate independent SQLDA structure */
size_t sqlda_size = XSQLDA_LENGTH(fb_query->out_fields_count);
result_query->out_sqlda = (XSQLDA *) emalloc(sqlda_size);
if (!result_query->out_sqlda) {
_php_fbird_module_error("SELECT: Failed to allocate SQLDA memory");
goto cleanup_select_result_query;
}
/* Safe copy of SQLDA header and variable array */
memcpy(result_query->out_sqlda, fb_query->out_sqlda, sqlda_size);
/* CRITICAL SAFETY FIX: Clear all sqldata pointers immediately to prevent
* double-free of parent data if allocation loop fails. */
for (int i = 0; i < fb_query->out_fields_count; i++) {
result_query->out_sqlda->sqlvar[i].sqldata = NULL;
}
/* Allocate independent null indicator array */
result_query->out_nullind = safe_emalloc(sizeof(*result_query->out_nullind),
fb_query->out_fields_count, 0);
if (!result_query->out_nullind) {
_php_fbird_module_error("SELECT: Failed to allocate null indicator array");
goto cleanup_select_result_query;
}
/* Safe copy of null indicators */
memcpy(result_query->out_nullind, fb_query->out_nullind,
sizeof(*result_query->out_nullind) * fb_query->out_fields_count);
/* Copy row buffers only when legacy path populated sqldata.
* In OO API mode, out_sqlda is metadata-only and fetch uses out_msg_buffer.
*/
for (int i = 0; i < fb_query->out_fields_count; i++) {
XSQLVAR *orig_var = &fb_query->out_sqlda->sqlvar[i];
XSQLVAR *result_var = &result_query->out_sqlda->sqlvar[i];
result_var->sqldata = NULL;
if (orig_var->sqldata) {
if (FAILURE == _php_fbird_safe_copy_sqlvar_data(result_var, orig_var, i, fb_query->query)) {
goto cleanup_select_result_query;
}
}
}
/* Update sqlind pointers to point to the new null indicators */
for (int i = 0; i < fb_query->out_fields_count; i++) {
if (result_query->out_sqlda->sqlvar[i].sqltype & 1) {
result_query->out_sqlda->sqlvar[i].sqlind = &result_query->out_nullind[i];
} else {
result_query->out_sqlda->sqlvar[i].sqlind = NULL;
}
}
/* Copy array metadata if present */
if (fb_query->out_array_cnt > 0 && fb_query->out_array) {
result_query->out_array_cnt = fb_query->out_array_cnt;
result_query->out_array = safe_emalloc(sizeof(fbird_array), fb_query->out_array_cnt, 0);
if (!result_query->out_array) {
_php_fbird_module_error("SELECT: Failed to allocate array metadata");
goto cleanup_select_result_query;
}
memcpy(result_query->out_array, fb_query->out_array,
sizeof(fbird_array) * fb_query->out_array_cnt);
}
}
/* Set result flags - parent query remains open, result has independent data */
result_query->has_more_rows = 1; /* Data is available for fetching */
result_query->is_open = 1; /* Result can be fetched */
/* Register the result as a new resource - this transfers ownership
* IMPORTANT: This result does NOT own the statement handle. */
result_query->owns_stmt_handle = 0;
result_query->res = zend_register_resource(result_query, le_query);
if (!result_query->res) {
_php_fbird_module_error("SELECT: Failed to register result resource");
goto cleanup_select_result_query;
}
/* Link this result as a child of the parent prepared query so that
* freeing the parent can invalidate dependent results (required for
* use-after-free tests). */
result_query->parent = fb_query;
result_query->child_head = NULL;
result_query->child_next = fb_query->child_head;
fb_query->child_head = result_query;
/* NOTE: We do NOT increment parent's refcount. The parent query resource
* lifetime is controlled by the user, not by child results. This allows
* multiple fbird_execute() calls on the same prepared query without the
* query resource becoming invalid after fbird_free_result(). */
/* Mark cursor state inherited from parent execute */
result_query->is_open = 1;
result_query->has_more_rows = 1;
/* Success - disable cleanup since resource system now owns the memory */
cleanup_needed = 0;
RETVAL_RES(result_query->res);
Z_TRY_ADDREF_P(return_value);
return SUCCESS;
cleanup_select_result_query:
/* Clean up partially allocated result_query on error path */
if (cleanup_needed && result_query) {
/* Free field data if partially allocated */
if (result_query->out_sqlda && result_query->out_fields_count > 0) {
for (int i = 0; i < result_query->out_fields_count; i++) {
if (result_query->out_sqlda->sqlvar[i].sqldata) {
efree(result_query->out_sqlda->sqlvar[i].sqldata);
}
}
}
/* Free SQLDA structure */
if (result_query->out_sqlda) {
efree(result_query->out_sqlda);
}
/* Free null indicator array */
if (result_query->out_nullind) {
efree(result_query->out_nullind);
}
/* Free array metadata */
if (result_query->out_array) {
efree(result_query->out_array);
}
/* Free query string */
if (result_query->query) {
efree(result_query->query);
}
/* NOTE: Do NOT free result_query->stmt as it's shared with parent */
/* Free the result query structure itself */
efree(result_query);
}
/* Propagate error to caller */
goto _php_fbird_ex_error;
}
}
/* Update cursor flags based on statement type and execution result */
switch (fb_query->statement_type) {
unsigned long affected_rows;
case isc_info_sql_stmt_insert:
case isc_info_sql_stmt_update:
case isc_info_sql_stmt_delete:
case isc_info_sql_stmt_exec_procedure:
affected_rows = 0;
/* OO API Only: compute affected rows via statement wrapper. */
if (fb_query->fbs_statement) {
ISC_UINT64 oo_affected = fbs_get_affected_records(
FBG(master_instance),
fb_query->fbs_statement,
status
);
if (FB_STATUS_ERROR(status)) {
_php_fbird_error(status);
goto _php_fbird_ex_error;
}
affected_rows = (unsigned long)oo_affected;
} else {
/* No OO API statement - cannot get affected rows */
_php_fbird_module_error("Cannot get affected rows: OO API statement required");
goto _php_fbird_ex_error;
}
fb_query->trans->affected_rows = affected_rows;
if (!fb_query->out_sqlda) { /* no result set is being returned */
/* Non-SELECT statements without RETURNING clause - no cursor opened */
fb_query->is_open = 0;
fb_query->has_more_rows = 0;
if (affected_rows) {
RETVAL_LONG(affected_rows);
} else {
RETVAL_TRUE;
}
break;
}
/* DML with RETURNING clause - cursor is opened but handled by result resource */
fb_query->is_open = 0;
fb_query->has_more_rows = 0;
break;