Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type-(un)safe unions (bug, and suggestion) ? #1168

Open
mwhicks1 opened this issue Aug 24, 2021 · 0 comments
Open

Type-(un)safe unions (bug, and suggestion) ? #1168

mwhicks1 opened this issue Aug 24, 2021 · 0 comments

Comments

@mwhicks1
Copy link
Contributor

I'm trying to understand how unions can be made type-safe in Checked C. I'm not seeing how. For example, this code type checks, but is not type-safe:

union u {
  _Array_ptr<int> p;
  _Nt_array_ptr<int> q;
};
_Checked void foo(_Array_ptr<int> p, union u s) {
  s.p = p;
  _Nt_array_ptr<int> q = s.q;
}

Here, we are converting an array pointer to an NT array pointer by writing to one field of the union and reading out of the other.

It might be nice to simply disallow unions in Checked regions, for the short term, or signal a warning of their use.

The typical way of using unions is to have a separate struct with a type tag and the union, where the type tag keeps track of the last field written to the union. This happens with Parson. It would be ideal to confirm that the programmer is doing the tag check properly, but that's not happening now.

My observation is that the type tag is similar to an array length, e.g.,

union u {
  int f_int;
  float f_float;
};
enum tag { INT, FLOAT };
struct tagunion {
  enum tag type;
  union u value : tag(type);
};

Here, I have added the tag annotation, and it's similar in spirit to the count annotation for arrays. It would be interpreted that the enum fields are ordered according to the fields in the union.

Just a thought. But in the meantime, unions seem like a hole in the type system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant