elvanderb

strlen without branches : Ugly C/compiler ""hack""

Sep 18th, 2012
432
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.43 KB | None | 0 0
  1. // compile with -O3 flag
  2. size_t strlen_no_condbr(char *s)
  3. {
  4.         size_t l=0;
  5.         void* ptr;
  6.         while (1)
  7.         {
  8.                 // ugly but gcc produce conditionnal branches if i don't do that
  9.                 goto *(void*) ( ((!!s[l])-1ll) & (long long)&&d | ((!!s[l])*-1ll) & (long long)&&i );
  10.                 i:
  11.                 l ++;
  12.         }
  13.         d:;
  14.         return l;
  15. }
  16.  
  17. size_t strlen_no_condbr2(char* s)
  18. {
  19.         size_t l = 0;
  20.         volatile int x = 0;
  21.         l --;
  22.         while (1)
  23.         {
  24.                 l++;
  25.                 switch ((unsigned char)s[l])
  26.                 {
  27.                         case 0:
  28.                                 break;
  29.                         case 1:
  30.                                 // random value so the compiler can't find a relation between s[l] and x
  31.                                 x = 205;
  32.                                 continue;
  33.                         case 2:
  34.                                 x = 102;
  35.                                 continue;
  36.                         [...]
  37.                         case 254:
  38.                                 x = 10;
  39.                                 continue;
  40.                         case 255:
  41.                                 x = 72;
  42.                                 continue;
  43.                         default :
  44.                                 continue;
  45.                 }
  46.                 break;
  47.         }
  48.         return l;
  49. }
Add Comment
Please, Sign In to add comment