On 2016-11-07 03:04, Andrei Borzenkov wrote: >> My initial idea matched your earlier example: >> >> #define STARTS_WITH(s1, s2) (strncmp((s1), (s2), sizeof(s2) - 1) == 0) >> >> Am I failing to see a use case where that breaks? >> > > char *prefix = "CRYPT-LUKS1-"; > sizeof (prefix) == 4 or 8 depending on platform. Not 13 in any case.
Yes, the second argument would always have to be a string literal. Not ideal, but I don't know a better way. Enforcing that the argument be a string literal would work, but I can't find a way to do that. The best I have come up with so far is this: #define STARTS_WITH(s1, s2) (strncmp((s1), (s2 ""), sizeof(s2) - 1) == 0) The string concatenation is intended to require s2 to be a string literal and fail at compilation time otherwise. Unfortunately, it is possible to defeat--s2 only has to _end_ with a string literal. It breaks with something like this: char *eight = "12345678" char *nine = "123456789" STARTS_WITH(eight, 1 ? nine : "foo")) >> The one bad thing I can see is that it can fail poorly if somebody reverses >> the arguments by mistake. In that case, sizeof(s2) returns the pointer size >> rather than the length of the string literal. I don't know how to enforce >> that a macro argument be a string literal. An alternate idea is: >> >> #define STARTS_WITH(s1, s2) (strncmp((s1), (s2), strlen(s2)) == 0) >> > > This adds additional overhead of function call instead of constant > expression; unless we are sure gcc/clang are smart enough to reduce it > for constant arguments. > >> That should work with arguments in either order (though of course s2 is >> expected to be smaller). I don't know of a drawback other than strlen >> presumably being a bit slower, but I didn't get the impression any of the >> code in question was performance-sensitive. >> > > For user space it probably does not matter much; but for boot time > code it also increases code size and better be avoided. > > Even for user space it is called often so if we can reduce overhead, > let's do it. I'm open to ideas. -Corey _______________________________________________ Grub-devel mailing list Grub-devel@gnu.org https://lists.gnu.org/mailman/listinfo/grub-devel