Skip to content

Commit

Permalink
Fix stack corruption when function returns pointer to its argument
Browse files Browse the repository at this point in the history
  • Loading branch information
nickg committed Aug 20, 2023
1 parent e63405f commit c3e1ed7
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/vcode.c
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ void vcode_heap_allocate(vcode_reg_t reg)
case VCODE_OP_ADDRESS_OF:
case VCODE_OP_LINK_VAR:
case VCODE_OP_LINK_PACKAGE:
case VCODE_OP_CONTEXT_UPREF:
break;

case VCODE_OP_ALLOC:
Expand Down Expand Up @@ -445,7 +446,13 @@ void vcode_heap_allocate(vcode_reg_t reg)
break;

case VCODE_OP_FCALL:
// Must have been safety checked by definition
for (int i = 0; i < defn->args.count; i++) {
const vtype_kind_t rkind = vcode_reg_kind(reg);
if (rkind == VCODE_TYPE_POINTER || rkind == VCODE_TYPE_UARRAY) {
// Function may return a pointer to its argument
vcode_heap_allocate(defn->args.items[i]);
}
}
break;

case VCODE_OP_RECORD_REF:
Expand Down
37 changes: 37 additions & 0 deletions test/regress/func25.vhd
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
entity func25 is
end entity;

architecture test of func25 is

function change_bounds (s : string; l, r : positive) return string is
alias ss : string(l to r) is s;
begin
return ss;
end function;

impure function get_string (c : character) return string is
variable s : string(1 to 15);
begin
s := "hello, world! " & c;
return change_bounds(s, 101, 115); -- Returns a pointer to S
end function;

function get_left (s : string) return positive is
begin
return s'left;
end function;

signal c : character := 'x';

begin

p1: process is
begin
wait for 1 ns;
report get_string(c);
assert get_string(c) = "hello, world! x";
assert get_left(get_string(c)) = 101;
wait;
end process;

end architecture;
1 change: 1 addition & 0 deletions test/regress/testlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -851,3 +851,4 @@ driver18 normal,2008
vhpi9 normal,vhpi
issue730 normal,2008
driver19 normal,2008
func25 normal

0 comments on commit c3e1ed7

Please sign in to comment.