;------------------------------------------------------------------------------
;
; Copyright (c) 2013, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution.  The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
;   AsmRdRand.Asm
;
; Abstract:
;
;   Implementation for 16-, 32-, and 64-bit invocations of RDRAND instruction under 64bit platform.
;
; Notes:
;
;   Visual Studio coding practices do not use inline asm since multiple compilers and 
;   architectures are supported assembler not recognizing rdrand instruction so using DB's.
;
;------------------------------------------------------------------------------

    .code

;------------------------------------------------------------------------------
;  Generate a 32 bit random number
;    Return TRUE if Rand generated successfully, or FALSE if not
;
;  BOOLEAN EFIAPI RdRand32Step (UINT32 *Rand);   RCX
;------------------------------------------------------------------------------
RdRand32StepEBX  PROC
    ; rdrand   ebx                 ; generate a 32 bit RN into eax, CF=1 if RN generated ok, otherwise CF=0
    push   rbx
    db     0fh, 0c7h, 0f3h         ; rdrand r32:  "0f c7 /6  ModRM:r/m(w)"
    jb     rn32_ok                 ; jmp if CF=1
    xor    ebx, ebx                ; reg=0 if CF=0
    pop    rbx
    ret                            ; return with failure status
rn32_ok:
    mov    [rcx], ebx
    mov    rax,  1
    pop    rbx
    ret
RdRand32StepEBX ENDP

;------------------------------------------------------------------------------
;  Generate a 32 bit random number
;    Return TRUE if Rand generated successfully, or FALSE if not
;
;  BOOLEAN EFIAPI RdRand32Step (UINT32 *Rand);   RCX
;------------------------------------------------------------------------------
RdRand32StepEDI  PROC
    ; rdrand   edi                 ; generate a 32 bit RN into eax, CF=1 if RN generated ok, otherwise CF=0
    push   rdi
    db     0fh, 0c7h, 0f7h         ; rdrand r32:  "0f c7 /6  ModRM:r/m(w)"
    jb     rn32_ok                 ; jmp if CF=1
    xor    edi, edi                ; reg=0 if CF=0
    pop    rdi
    ret                            ; return with failure status
rn32_ok:
    mov    [rcx], edi
    mov    rax,  1
    pop    rdi
    ret
RdRand32StepEDI ENDP

    END
