Skip to content

[Alan] Handling string literal modifications #39

Description

@andreasstamos

Let's consider the following Alan program.

main () : proc
  foo (arr: reference byte []) : proc {
    arr[0] = 'a';
    writeString(arr);
  }
{
  foo("fgh");
}

The equivalent program in C:

#include<stdio.h>

void foo (char *arr) {
  arr[0] = 'd';
  printf("%s", arr);
}

int main(void) {
  foo("fgh");
}

crashes with segmentation fault when compiled both with GCC and Clang. By inspecting the LLVM IR, it is observed that Clang marks the array with the constant attribute, causing the LLVM compiler to place it in the .rodata segment, which leads to the crash.

The C standard (https://en.cppreference.com/w/c/language/string_literal) states: "String literals are not modifiable (and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined."

Alan does not have a const qualifier for its types. There seem to be three options for the above case:

  1. Let the program crash at runtime. (This is our current implementation.)
  2. In LLVM IR, for all string literals, use the global attribute instead of constant for the array, making it modifiable. This will cause LLVM to place the array in the .data segment.
  3. Analyze the function body to check if write operations are performed on an array argument. If writes are detected, there are two possible actions:
    a. For the affected function call, convert the string literal into a global, modifiable array.
    b. Issue a semantic error or warning.
    (Essentially, this would introduce an implicit const qualifier-like behavior in array types.)

Interestingly, since C++11, C++ protects programmers from modifying string literals through the type system, unless explicitly intended. The C++ reference (https://en.cppreference.com/w/cpp/language/string_literal) states:
"String literals are not convertible or assignable to non-const CharT*. An explicit cast (e.g. const_cast) must be used if such conversion is wanted."

What is the expected behavior for handling string literal modifications in Alan?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions