【问题标题】:Is there any larger significance to this piece of translated assembly code?这段翻译后的汇编代码有什么更大的意义吗?
【发布时间】:2015-06-01 06:26:42
【问题描述】:

对于 CS 架构中的简短家庭作业,我们被要求将以下 IA-32 程序集翻译成 C。我已经正确翻译了它(据我所知),但代码没有'似乎没有做任何特别有用的事情。我的教授通常会给我们这样的问题,最终会做一些事情:我们上一个这样的作业有点 pop_count。看看下面的 C 代码,这个函数有什么用处吗?也许是某种算法?

代码如下所示(我已将 cmets 添加到每个 ASM 行)。

// The following variables x, y, z are located at (%ebp) +8, +12, +16 respectively
// x, y, and z, are scanned from the terminal and passed into the function

   movl 12(%ebp), %edx                  // moves long y to register %edx
   subl 16(%ebp), %edx                  // subtracts longs: y = y - z
   movl %edx, %eax                      // moves long y to register %eax
   sall $31, %eax                       // left shift all bits in long y by 31 places 
   sarl $31, %eax                       // arithmetic right shift long y by 31 places
   imull 8(%ebp), %edx                  // multiply longs: unshifted y = y * x
   xorl %edx, %eax                      // XOR operation: shifted y = shifted y ^ unshifted y

// The returned value is stored in register %eax

有效的外卖是我们从 y 中减去 z,然后用最低有效位填充每个位以形成零或 MAX_UINT。这是与 (y - z) * x 的乘积进行异或运算并返回。

我的 C 翻译:

return (((y - z) << 31) >> 31) ^ ((y - z) * x);

// In more words:
    int f;
    y -= z;
    f = y << 31;                        // These two lines populate all bits with the lsb
    f = f >> 31;                        // Effectively, if y-z is odd: f is ~0; else f is 0
    y *= x;
    return y ^ f;

// Or, using people logic:
    y -= z;
    if (y % 2 == 0) return y * x;
    return -(y * x) - 1;

// If the y-z is odd, the result will be:    -1 * ((y - z) * x) - 1
// If the y-z is even, the result will be:              (y - z) * x

为了澄清,这不是硬件任务的一部分;我已经通过翻译代码完成了任务,但我很想知道他为什么一开始就给了我们这个代码。

【问题讨论】:

    标签: c algorithm assembly x86 reverse-engineering


    【解决方案1】:

    我的猜测是您的教授试图说明如何使用位移/屏蔽操作来避免分支。如果你天真地翻译

    y -= z;
    if (y % 2 == 0) return y * x;
    return -(y * x) - 1;
    

    在机器码中,您可以使用条件分支指令。分支会大大减慢您的代码速度,尤其是当它们处于紧密循环中时*。汇编代码和您前面的 C 代码具有使用条件判断 y - z 是否为偶数的效果,但仅使用算术指令。

    *如果你还不熟悉这个事实,this SO answer 有我最喜欢的插图之一。

    【讨论】:

    • 您提出的观点很有趣。事实上,我的教授说这部分是为了展示在没有条件分支的情况下执行逻辑的能力。感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2023-03-14
    • 1970-01-01
    • 2021-07-25
    • 2012-06-29
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多