VirtualBox

Changeset 51770 in vbox


Ignore:
Timestamp:
Jul 1, 2014 6:14:02 PM (11 years ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
94611
Message:

Merged in iprt++ dev branch.

Location:
trunk
Files:
161 added
2 deleted
83 edited

Legend:

Unmodified
Added
Removed
  • trunk

  • trunk/Config.kmk

    r51533 r51770  
    741741# Most developers will want to disable this in their LocalConfig.kmk.
    742742ifn1of ($(KBUILD_TARGET), win)
    743  VBOX_WITH_HARDENING = 1
     743VBOX_WITH_HARDENING = 1
    744744endif
    745745# Where the application files are (going to be) installed.
     
    803803endif
    804804# Enable the system wide support service/daemon.
    805 # Work in progress, but required for hardening on Windows.
     805# Very sketchy work in progress.
    806806#VBOX_WITH_SUPSVC = 1
    807 ifdef VBOX_WITH_HARDENING
    808  if1of ($(KBUILD_TARGET), win)
    809   VBOX_WITH_SUPSVC = 1
    810  endif
    811 endif
    812807## @}
    813808
     
    18451840VBOX_RTMANIFEST ?= $(PATH_OBJ)/bldRTManifest/bldRTManifest$(HOSTSUFF_EXE)
    18461841
     1842# RTSignTool (certificate extraction tool)
     1843VBOX_RTSIGNTOOL ?= $(PATH_OBJ)/bldRTSignTool/bldRTSignTool$(HOSTSUFF_EXE)
     1844
    18471845# VBoxCmp (simple /bin/cmp with more sensible output)
    18481846VBOX_VBOXCMP    ?= $(PATH_OBJ)/VBoxCmp/VBoxCmp$(HOSTSUFF_EXE)
     
    18561854# VBoxPeSetVersion (changes the minimum OS version of an image)
    18571855VBOX_PE_SET_VERSION ?= $(PATH_OBJ)/VBoxPeSetVersion/VBoxPeSetVersion$(HOSTSUFF_EXE)
     1856
     1857# Visual C++ EditBin.exe.
     1858VBOX_VCC_EDITBIN = $(if $(PATH_TOOL_$(VBOX_VCC_TOOL)_BIN),$(PATH_TOOL_$(VBOX_VCC_TOOL)_BIN)/,)editbin.exe /NoLogo
    18581859
    18591860# filesplitter (splits java files)
     
    26292630
    26302631  ## Commands for signing a driver image after link.
    2631   VBOX_SIGN_DRIVER_CMDS ?= $(if $(eq $(tool_do),LINK_LIBRARY),,$(call VBOX_SIGN_FILE_FN,$(out)))
    2632   ## Sign a file.
     2632  VBOX_SIGN_DRIVER_CMDS ?= $(if $(eq $(tool_do),LINK_LIBRARY),,$(call VBOX_SIGN_IMAGE_FN,$(out)))
     2633  ## Sign a file (generic).
    26332634  # @param 1  The file to sign.
    26342635  # @param 2  File description. Optional.
     2636  # @param 3  Additional parameters. Optional.
    26352637  VBOX_SIGN_FILE_FN     ?= $(VBOX_SIGNTOOL) sign \
    26362638        $(VBOX_CROSS_CERTIFICATE_FILE_ARGS) \
     
    26392641        $(VBOX_TSA_URL_ARGS) \
    26402642        $(if $(strip $(2)),/d "$(strip $(2))",) \
     2643       $(3) \
    26412644        $(1)
     2645  ## Sign an executable image.
     2646  # @param 1  The file to sign.
     2647  # @param 2  File description. Optional.
     2648  VBOX_SIGN_IMAGE_FN     ?= $(call VBOX_SIGN_FILE_FN,$(1),$(2),/ph)
     2649
    26422650  ## Create a security catalog file.
    26432651  # @param 1  The directory containing the stuff to sign.
     
    26582666
    26592667  # Go nuts, sign everything.
    2660   ifeq ($(strip $(VBOX_SIGNING_MODE)),release)
     2668  if "$(strip $(VBOX_SIGNING_MODE))" == "release" || defined(VBOX_WITH_HARDENING)
    26612669   ## Commands for signing an executable or a dll image after link.
    2662    VBOX_SIGN_IMAGE_CMDS  ?= $(if $(eq $(tool_do),LINK_LIBRARY),,$(call VBOX_SIGN_FILE_FN,$(out)))
     2670   VBOX_SIGN_IMAGE_CMDS  ?= $(if $(eq $(tool_do),LINK_LIBRARY),,$(call VBOX_SIGN_IMAGE_FN,$(out)))
    26632671  endif
    26642672  ## Enable signing of the additions.
     
    27482756        $(1)
    27492757
     2758##
     2759# Helper macro for re-signing DLL images from tools that we ship so they won't
     2760# cause trouble for the hardened build requirements.
     2761#
     2762# Invoke via $(call VBOX_RE_SIGN_DLL_FN) inside the SOURCES list.  Necessary
     2763# _CLEAN entry will be added to the target.  If hardening is not enabled or
     2764# we're not on windows, the source will be returned.
     2765#
     2766# @returns  Name of the output file name.  May have leading space, but no trailing.
     2767# @param    1   Target name.
     2768# @param    2   The source name.
     2769#
     2770if defined(VBOX_SIGNING_MODE) && "$(KBUILD_TARGET)" == "win"
     2771 VBOX_RE_SIGN_DLL_FN = $(if-expr !defined($(1)_VBOX_RE_SIGNED_$(notdir $(2))),\
     2772        $(evalcall VBOX_RE_SIGN_DLL_INTERNAL_FN,$1,$2)\
     2773        ,)$($(1)_0_OUTDIR)/$(notdir $2)
     2774
     2775define VBOX_RE_SIGN_DLL_INTERNAL_FN
     2776local n = $(notdir $2)
     2777ifndef $(1)_VBOX_RE_SIGNED_$(n)
     2778 $(1)_VBOX_RE_SIGNED_$(n) := 1
     2779 $(eval $(1)_CLEAN += $$($(1)_0_OUTDIR)/$(n))
     2780
     2781 $$($(1)_0_OUTDIR)/$(n): $(2) $(VBOX_VERSION_STAMP) | $$(dir $$@)
     2782        $(call MSG_TOOL,SIGNTOOL,,$<,$@)
     2783        $(RM) -f -- "$@"
     2784        $(CP) -- "$<" "$@"
     2785        $(VBOX_VCC_EDITBIN) /LargeAddressAware /DynamicBase /NxCompat /Release /IntegrityCheck \
     2786                /Version:$(VBOX_VERSION_MAJOR)0$(VBOX_VERSION_MINOR).$(VBOX_VERSION_BUILD) \
     2787                "$@"
     2788        $(call VBOX_SIGN_IMAGE_FN,$@)
     2789endif
     2790endef # VBOX_RESIGN_DLL_FN
     2791else
     2792 VBOX_RE_SIGN_DLL_FN = $(2)
     2793endif
     2794
     2795
     2796##
     2797# @param
     2798VBOX_RESIGN_DLL_FN =
     2799
    27502800#
    27512801# Adjust kBuild defaults.
     
    28692919        $(PATH_STAGE_LIB)/VBoxExtPack-libssl$(VBOX_SUFF_LIB) \
    28702920        $(PATH_STAGE_LIB)/VBoxExtPack-libcrypto$(VBOX_SUFF_LIB)
     2921
     2922if "$(KBUILD_TARGET)" == "win" && defined(VBOX_WITH_HARDENING)
     2923 SDK_VBoxOpenSslHardened                = Only for VBoxDrv and Hardened Stub EXEs on windows.
     2924 SDK_VBoxOpenSslHardened_INCS           = $(SDK_VBOX_OPENSSL_VBOX_DEFAULT_INCS)
     2925 SDK_VBoxOpenSslHardened_ORDERDEPS      = $(crypto-headers_1_TARGET)
     2926 SDK_VBoxOpenSslHardened_LIBS           = \
     2927        $(PATH_STAGE_LIB)/VBoxHardened-libcrypto$(VBOX_SUFF_LIB)
     2928endif
    28712929
    28722930SDK_VBOX_BLD_OPENSSL      = .
     
    30833141  endif
    30843142  TEMPLATE_VBoxRc_CFLAGS             = $(TEMPLATE_VBoxRc_CXXFLAGS)
    3085   TEMPLATE_VBoxRc_LDFLAGS            = -Driver -Subsystem:NATIVE -Incremental:NO -Align:64 -MapInfo:Exports -NoD $(VBOX_VCC_LD_WERR) -Debug
     3143  TEMPLATE_VBoxRc_LDFLAGS            = -Driver -Subsystem:NATIVE -Incremental:NO -Align:64 -MapInfo:Exports -NoD $(VBOX_VCC_LD_WERR) -Release -Debug
     3144  ifdef VBOX_SIGNING_MODE
     3145   TEMPLATE_VBoxRc_LDFLAGS          += -IntegrityCheck
     3146  endif
    30863147  TEMPLATE_VBoxRc_LIBS               = \
    30873148        $(PATH_SDK_$(VBOX_WINDDK)_LIB.x86)/int64.lib
     
    32063267 endif
    32073268TEMPLATE_VBoxR0_CFLAGS              = $(TEMPLATE_VBoxR0_CXXFLAGS)
    3208 TEMPLATE_VBoxR0_LDFLAGS             = -Driver -Subsystem:NATIVE -Incremental:NO -Align:4096 -MapInfo:Exports -NoD $(VBOX_VCC_LD_WERR) -Debug
     3269TEMPLATE_VBoxR0_LDFLAGS             = -Driver -Subsystem:NATIVE -Incremental:NO -Align:4096 -MapInfo:Exports -NoD $(VBOX_VCC_LD_WERR) -Release -Debug
    32093270 ifdef VBOX_WITH_DTRACE_R0
    32103271TEMPLATE_VBoxR0_LDFLAGS            += -Merge:VTGPrLc.Data=VTGPrLc.Begin -Merge:VTGPrLc.End=VTGPrLc.Begin -Merge:VTGPrLc.Begin=VTGObj
     3272 endif
     3273 ifdef VBOX_SIGNING_MODE
     3274  TEMPLATE_VBoxR0_LDFLAGS          += -IntegrityCheck
    32113275 endif
    32123276TEMPLATE_VBoxR0_LIBS                = \
     
    33083372 TEMPLATE_VBOXR0DRV_DEFS.x86          += WIN9X_COMPAT_SPINLOCK     # Avoid multiply defined _KeInitializeSpinLock@4
    33093373 TEMPLATE_VBOXR0DRV_DEFS.amd64         = _AMD64_
    3310  TEMPLATE_VBOXR0DRV_CXXFLAGS           = -Zi -Zl -GR- -EHs- -GF -Gz -W3 -GS- -wd4996 -Zc:wchar_t- $(VBOX_VCC_OPT) $(VBOX_VCC_FP)
     3374 TEMPLATE_VBOXR0DRV_CXXFLAGS           = -Zi -Zl -GR- -EHs- -GF -Gz -W3 -GS- -wd4996 -Zc:wchar_t- -Gs4096 $(VBOX_VCC_OPT) $(VBOX_VCC_FP)
    33113375 TEMPLATE_VBOXR0DRV_CFLAGS             = $(TEMPLATE_VBOXR0DRV_CXXFLAGS)
    3312  TEMPLATE_VBOXR0DRV_LDFLAGS            = -Driver -Subsystem:NATIVE -Incremental:NO -Align:4096 -MapInfo:Exports -NoD -Debug
     3376 TEMPLATE_VBOXR0DRV_LDFLAGS            = -Driver -Subsystem:NATIVE -Incremental:NO -Align:4096 -MapInfo:Exports -NoD -Release -Debug
    33133377 ifdef VBOX_WITH_DTRACE_R0DRV
    33143378  TEMPLATE_VBOXR0DRV_LDFLAGS          += -Merge:VTGPrLc.Data=VTGPrLc.Begin -Merge:VTGPrLc.End=VTGPrLc.Begin -Merge:VTGPrLc.Begin=VTGObj
     3379 endif
     3380 ifdef VBOX_SIGNING_MODE
     3381  TEMPLATE_VBOXR0DRV_LDFLAGS          += -IntegrityCheck
    33153382 endif
    33163383 TEMPLATE_VBOXR0DRV_POST_CMDS          = $(VBOX_SIGN_DRIVER_CMDS)
     
    36053672 TEMPLATE_VBOXR3EXE_CFLAGS.kprofile    = $(TEMPLATE_VBOXR3EXE_CXXFLAGS.kprofile)
    36063673 TEMPLATE_VBOXR3EXE_LDFLAGS            = \
    3607         /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LARGEADDRESSAWARE /DEBUG \
     3674        /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LargeAddressAware /DynamicBase /NxCompat /Release /Debug \
     3675        /Version:$(VBOX_VERSION_MAJOR)0$(VBOX_VERSION_MINOR).$(VBOX_VERSION_BUILD) \
    36083676        /DISALLOWLIB:libc.lib \
    36093677        /DISALLOWLIB:libcd.lib \
     
    36143682 ifdef VBOX_WITH_DTRACE_R3
    36153683  TEMPLATE_VBOXR3EXE_LDFLAGS          += -Merge:VTGPrLc.Data=VTGPrLc.Begin -Merge:VTGPrLc.End=VTGPrLc.Begin -Merge:VTGPrLc.Begin=VTGObj
     3684 endif
     3685 if defined(VBOX_SIGNING_MODE) && defined(VBOX_WITH_HARDENING)
     3686   TEMPLATE_VBOXR3EXE_LDFLAGS         += -IntegrityCheck
    36163687 endif
    36173688
     
    39263997TEMPLATE_VBOXR3HARDENEDEXE = Hardened VBox Ring-3 EXE
    39273998TEMPLATE_VBOXR3HARDENEDEXE_EXTENDS = VBOXR3EXE
     3999TEMPLATE_VBOXR3HARDENEDEXE_DEBUG_INST.win = $(INST_DEBUG)hardened-exes/
    39284000TEMPLATE_VBOXR3HARDENEDEXE_LIBS = $(VBOX_LIB_SUPHARDENED) $(TEMPLATE_VBOXR3EXE_LIBS)
    39294001TEMPLATE_VBOXR3HARDENEDEXE_LDFLAGS.darwin = $(TEMPLATE_VBOXR3EXE_LDFLAGS.darwin) -framework IOKit
     
    39334005endif
    39344006ifeq ($(KBUILD_TARGET),win) # No CRT!
     4007 TEMPLATE_VBOXR3HARDENEDEXE_SDKS          = VBOX_NTDLL $(TEMPLATE_VBOXR3EXE_SDKS) VBoxOpenSslHardened
    39354008 TEMPLATE_VBOXR3HARDENEDEXE_LIBS.x86      = \
     4009        $(PATH_SDK_$(VBOX_WINDDK)_LIB.x86)/int64.lib \
    39364010        $(PATH_TOOL_$(TEMPLATE_VBOXR3HARDENEDEXE_TOOL.win.x86)_LIB)/chkstk.obj
    3937  TEMPLATE_VBOXR3HARDENEDEXE_LIBS.amd64    = \
    3938         $(PATH_TOOL_$(TEMPLATE_VBOXR3HARDENEDEXE_TOOL.win.amd64)_LIB)/chkstk.obj
    39394011 TEMPLATE_VBOXR3HARDENEDEXE_CXXFLAGS      = $(filter-out -RTC% -GZ -GS,$(TEMPLATE_VBOXR3EXE_CXXFLAGS)) -GS-
    39404012 TEMPLATE_VBOXR3HARDENEDEXE_CXXFLAGS.debug= $(filter-out -RTC% -GZ -GS,$(TEMPLATE_VBOXR3EXE_CXXFLAGS.debug)) -GS-
     
    40314103if "$(KBUILD_TARGET)" == "win" && defined(VBOX_SIGNING_MODE)
    40324104 TEMPLATE_VBOXR3AUTOTST_POST_CMDS = $(NO_SUCH_VARIABLE)
     4105 TEMPLATE_VBOXR3AUTOTST_LDFLAGS = $(filter-out -IntegrityCheck, $(TEMPLATE_VBoxR3Static_LDFLAGS))
    40334106endif
    40344107
     
    40484121if "$(KBUILD_TARGET)" == "win" && defined(VBOX_SIGNING_MODE)
    40494122 TEMPLATE_VBOXR3TSTEXE_POST_CMDS =
     4123 TEMPLATE_VBOXR3TSTEXE_LDFLAGS = $(filter-out -IntegrityCheck, $(TEMPLATE_VBOXR3EXE_LDFLAGS))
    40504124endif
    40514125
     
    42354309 TEMPLATE_VBOXMAINEXE_CFLAGS.kprofile    = $(TEMPLATE_VBOXMAINEXE_CXXFLAGS.kprofile)
    42364310 TEMPLATE_VBOXMAINEXE_LDFLAGS            = \
    4237         /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LARGEADDRESSAWARE /DEBUG\
     4311        /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LargeAddressAware /DynamicBase /NxCompat /Release /Debug \
     4312        /Version:$(VBOX_VERSION_MAJOR)0$(VBOX_VERSION_MINOR).$(VBOX_VERSION_BUILD) \
    42384313        /DISALLOWLIB:libc.lib \
    42394314        /DISALLOWLIB:libcd.lib \
     
    42424317        /DISALLOWLIB:msvcrt$(VBOX_VCC_CRT_TYPE_N).lib \
    42434318        /DISALLOWLIB:msvcprt$(VBOX_VCC_CRT_TYPE_N).lib
     4319 if defined(VBOX_SIGNING_MODE) && defined(VBOX_WITH_HARDENING)
     4320  TEMPLATE_VBOXMAINEXE_LDFLAGS          += -IntegrityCheck
     4321 endif
    42444322 TEMPLATE_VBOXMAINEXE_LIBS               = \
    42454323        $(LIB_RUNTIME)
     
    46884766        $(PATH_TOOL_$(VBOX_VCC_TOOL)_ATLMFC_INC)
    46894767  TEMPLATE_VBOXQT4GUIEXE_LDFLAGS = \
    4690         /NOD /NOLOGO /INCREMENTAL:NO /MAPINFO:EXPORTS /DEBUG
     4768        /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LargeAddressAware /DynamicBase /NxCompat /Release /Debug \
     4769        /Version:$(VBOX_VERSION_MAJOR)0$(VBOX_VERSION_MINOR).$(VBOX_VERSION_BUILD)
     4770  if defined(VBOX_SIGNING_MODE) && defined(VBOX_WITH_HARDENING)
     4771   TEMPLATE_VBOXQT4GUIEXE_LDFLAGS += -IntegrityCheck
     4772  endif
    46914773  TEMPLATE_VBOXQT4GUIEXE_SDKS += $(VBOX_WINPSDK)
    46924774  TEMPLATE_VBOXQT4GUIEXE_LIBS = \
     
    47054787  endif
    47064788  TEMPLATE_VBOXQT4GUIEXE_POST_CMDS = $(VBOX_SIGN_IMAGE_CMDS)
    4707   TEMPLATE_VBOXQT4GUIEXE_LDFLAGS.win.x86 += /LARGEADDRESSAWARE
    47084789
    47094790 else # the gcc guys:
     
    48724953 TEMPLATE_VBoxBldProg_CFLAGS.kprofile    = $(TEMPLATE_VBoxBldProg_CXXFLAGS.kprofile)
    48734954 TEMPLATE_VBoxBldProg_LDFLAGS            = \
    4874         /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LARGEADDRESSAWARE /DEBUG \
     4955        /NOD /INCREMENTAL:NO /MAPINFO:EXPORTS /LargeAddressAware /DynamicBase /NxCompat /Release /Debug \
     4956        /Version:$(VBOX_VERSION_MAJOR)0$(VBOX_VERSION_MINOR).$(VBOX_VERSION_BUILD) \
    48754957        /DISALLOWLIB:libc$(VBOX_VCC_CRT_TYPE_N).lib \
    48764958        /DISALLOWLIB:libcmt$(VBOX_VCC_CRT_TYPE_N).lib \
  • trunk/Makefile.kmk

    r51368 r51770  
    2222# Sub-makefiles / Sub-directories.
    2323#
    24 if defined(VBOX_WITH_DOCS) && (!defined(VBOX_ONLY_BUILD) || defined(VBOX_ONLY_DOCS) || defined(VBOX_ONLY_SDK))
    25  include $(PATH_SUB_CURRENT)/doc/manual/Makefile.kmk
    26 endif
    27 include $(PATH_SUB_CURRENT)/src/Makefile.kmk
     24ifndef VBOX_ONLY_ROOT_MAKEFILE
     25 if defined(VBOX_WITH_DOCS) && (!defined(VBOX_ONLY_BUILD) || defined(VBOX_ONLY_DOCS) || defined(VBOX_ONLY_SDK))
     26  include $(PATH_SUB_CURRENT)/doc/manual/Makefile.kmk
     27 endif
     28 include $(PATH_SUB_CURRENT)/src/Makefile.kmk
     29endif
    2830
    2931#
     
    9193  include $(KBUILD_PATH)/sdks/LIBSDL.kmk
    9294  InstallExternalLibs_SOURCES += \
    93         $(DLL_SDK_LIBSDL_SDL)
     95        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(DLL_SDK_LIBSDL_SDL))
    9496  ifdef VBOX_WITH_SECURELABEL
    9597   InstallExternalLibs_SOURCES += \
    96         $(DLL_SDK_LIBSDL_SDLTTF)
     98        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(DLL_SDK_LIBSDL_SDLTTF))
    9799  endif
    98100  ifeq ($(KBUILD_TARGET),os2)
     
    106108# The compiler runtime DLLs.
    107109ifeq ($(KBUILD_TARGET).$(VBOX_WITHOUT_COMPILER_REDIST),win.)
    108   VBOX_PATH_VCC_REDIST         = $(PATH_TOOL_$(VBOX_VCC_TOOL))/redist/
    109   VBOX_PATH_VCC_REDIST_CRT     = $(VBOX_PATH_VCC_REDIST)/$(subst amd64,x64,$(KBUILD_TARGET_ARCH))/Microsoft.VC100.CRT
    110   VBOX_PATH_VCC_REDIST_CRT_DBG = $(VBOX_PATH_VCC_REDIST)/Debug_NonRedist/$(subst amd64,x64,$(KBUILD_TARGET_ARCH))/Microsoft.VC100.DebugCRT
     110 include $(KBUILD_PATH)/tools/$(VBOX_VCC_TOOL).kmk
     111 include $(KBUILD_PATH)/tools/$(VBOX_VCC_TOOL_STEM)X86.kmk
     112 VBOX_PATH_VCC_REDIST             = $(PATH_TOOL_$(VBOX_VCC_TOOL))/redist/
     113 VBOX_PATH_VCC_REDIST_CRT         = $(VBOX_PATH_VCC_REDIST)/$(subst amd64,x64,$(KBUILD_TARGET_ARCH))/Microsoft.VC100.CRT
     114 VBOX_PATH_VCC_REDIST_CRT_DBG     = $(VBOX_PATH_VCC_REDIST)/Debug_NonRedist/$(subst amd64,x64,$(KBUILD_TARGET_ARCH))/Microsoft.VC100.DebugCRT
     115 VBOX_PATH_VCC_REDIST_CRT_X86     = $(VBOX_PATH_VCC_REDIST)/x86/Microsoft.VC100.CRT
     116 VBOX_PATH_VCC_REDIST_CRT_DBG_X86 = $(VBOX_PATH_VCC_REDIST)/Debug_NonRedist/x86/Microsoft.VC100.DebugCRT
     117
     118 InstallExternalLibs_SOURCES += \
     119        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll) \
     120        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll) \
     121        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>testcase/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
     122        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>testcase/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
     123 ifdef VBOX_WITH_32_ON_64_MAIN_API
    111124  InstallExternalLibs_SOURCES += \
    112         $(VBOX_PATH_VCC_REDIST_CRT)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    113         $(VBOX_PATH_VCC_REDIST_CRT)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    114         $(VBOX_PATH_VCC_REDIST_CRT)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>testcase/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    115         $(VBOX_PATH_VCC_REDIST_CRT)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>testcase/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
    116  ifdef VBOX_WITH_32_ON_64_MAIN_API
    117   VBOX_PATH_VCC_REDIST_CRT_X86 = $(VBOX_PATH_VCC_REDIST)/x86/Microsoft.VC100.CRT
    118   VBOX_PATH_VCC_REDIST_CRT_DBG_X86 = $(VBOX_PATH_VCC_REDIST)/Debug_NonRedist/x86/Microsoft.VC100.DebugCRT
    119   InstallExternalLibs_SOURCES += \
    120         $(VBOX_PATH_VCC_REDIST_CRT_X86)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>x86/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    121         $(VBOX_PATH_VCC_REDIST_CRT_X86)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>x86/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
     125        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_X86)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>x86/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
     126        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_X86)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>x86/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
    122127 endif
    123128 ifeq ($(VBOX_VCC_CRT_TYPE),d)
    124129  InstallExternalLibs_SOURCES += \
    125         $(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    126         $(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    127         $(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>testcase/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    128         $(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>testcase/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
     130        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll) \
     131        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll) \
     132        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>testcase/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
     133        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_DBG)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>testcase/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
    129134  ifdef VBOX_WITH_32_ON_64_MAIN_API
    130135  InstallExternalLibs_SOURCES += \
    131         $(VBOX_PATH_VCC_REDIST_CRT_DBG_X86)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>x86/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
    132         $(VBOX_PATH_VCC_REDIST_CRT_DBG_X86)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll=>x86/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
     136        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_DBG_X86)/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>x86/msvcr$(substr $(VBOX_VCC_TOOL_STEM),4).dll \
     137        $(call VBOX_RE_SIGN_DLL_FN,InstallExternalLibs,$(VBOX_PATH_VCC_REDIST_CRT_DBG_X86)/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll)=>x86/msvcp$(substr $(VBOX_VCC_TOOL_STEM),4).dll
    133138  endif
    134139 endif
     
    168173   qt4-bin_INST = $(INST_BIN)
    169174   qt4-bin_SOURCES = \
    170         $(foreach qtmod,$(VBOX_QT4_MOD_NAMES),$(VBOX_PATH_QT4_LIB)/$(qtmod)4$(SUFF_DLL)) \
    171         $(VBOX_PATH_QT4)/plugins/accessible/qtaccessiblewidgets4$(SUFF_DLL)=>accessible/qtaccessiblewidgets4$(SUFF_DLL)
     175        $(foreach qtmod,$(VBOX_QT4_MOD_NAMES),$(call VBOX_RE_SIGN_DLL_FN,qt4-bin,$(VBOX_PATH_QT4_LIB)/$(qtmod)4$(SUFF_DLL))) \
     176        $(call VBOX_RE_SIGN_DLL_FN,qt4-bin,$(VBOX_PATH_QT4)/plugins/accessible/qtaccessiblewidgets4$(SUFF_DLL))=>accessible/qtaccessiblewidgets4$(SUFF_DLL)
    172177  else
    173178   INSTALLS += qt4-bin
  • trunk/include/Makefile.kmk

    r43387 r51770  
    9595        iprt/thread.h \
    9696        iprt/mem.h \
     97        iprt/memsafer.h \
    9798        iprt/alloc.h \
    9899        $(r3_cpp_hdrs) \
  • trunk/include/VBox/err.h

    r51757 r51770  
    17551755/** The user mode tracepoint provider string table offset is bad. */
    17561756#define VERR_SUPDRV_TRACER_UMOD_STRTAB_OFF_BAD      (-3737)
     1757/** The VM process was denied access to vboxdrv because someone have managed to
     1758 * open the process or its main thread with too broad access rights. */
     1759#define VERR_SUPDRV_HARDENING_EVIL_HANDLE           (-3738)
     1760/** Error opening the ApiPort LPC object. */
     1761#define VERR_SUPDRV_APIPORT_OPEN_ERROR              (-3739)
     1762/** Error enumerating all processes in the session. */
     1763#define VERR_SUPDRV_SESSION_PROCESS_ENUM_ERROR      (-3740)
     1764/** The CSRSS instance associated with the client process could not be
     1765 * located. */
     1766#define VERR_SUPDRV_CSRSS_NOT_FOUND                 (-3741)
    17571767/** @} */
    17581768
     
    18021812/** The internal application does not reside in the correct place (hardening). */
    18031813#define VERR_SUPLIB_INVALID_INTERNAL_APP_DIR        (-3769)
     1814/** Unable to establish trusted of VM process (0). */
     1815#define VERR_SUPLIB_NT_PROCESS_UNTRUSTED_0          (-3770)
     1816/** Unable to establish trusted of VM process (1). */
     1817#define VERR_SUPLIB_NT_PROCESS_UNTRUSTED_1          (-3771)
     1818/** Unable to establish trusted of VM process (2). */
     1819#define VERR_SUPLIB_NT_PROCESS_UNTRUSTED_2          (-3772)
     1820/** Unable to establish trusted of VM process (3). */
     1821#define VERR_SUPLIB_NT_PROCESS_UNTRUSTED_3          (-3773)
     1822/** Unable to establish trusted of VM process (4). */
     1823#define VERR_SUPLIB_NT_PROCESS_UNTRUSTED_4          (-3774)
     1824/** Unable to establish trusted of VM process (5). */
     1825#define VERR_SUPLIB_NT_PROCESS_UNTRUSTED_5          (-3775)
    18041826/** @} */
    18051827
     
    23112333
    23122334
     2335/** @name Support driver/library shared verfication status codes.
     2336 * @{  */
     2337/** Process Verficiation Failure: The memory content does not match the image
     2338 *  file. */
     2339#define VERR_SUP_VP_MEMORY_VS_FILE_MISMATCH          (-5600)
     2340/** Process Verficiation Failure: The memory protection of a image file section
     2341 *  does not match what the section header prescribes. */
     2342#define VERR_SUP_VP_SECTION_PROTECTION_MISMATCH      (-5601)
     2343/** Process Verficiation Failure: One of the section in the image file is not
     2344 *  mapped into memory. */
     2345#define VERR_SUP_VP_SECTION_NOT_MAPPED               (-5602)
     2346/** Process Verficiation Failure: One of the section in the image file is not
     2347 *  fully mapped into memory. */
     2348#define VERR_SUP_VP_SECTION_NOT_FULLY_MAPPED         (-5603)
     2349/** Process Verficiation Failure: Bad file alignment value in image header. */
     2350#define VERR_SUP_VP_BAD_FILE_ALIGNMENT_VALUE         (-5604)
     2351/** Process Verficiation Failure: Bad image base in header. */
     2352#define VERR_SUP_VP_BAD_IMAGE_BASE                   (-5605)
     2353/** Process Verficiation Failure: Bad image signature. */
     2354#define VERR_SUP_VP_BAD_IMAGE_SIGNATURE              (-5606)
     2355/** Process Verficiation Failure: Bad image size. */
     2356#define VERR_SUP_VP_BAD_IMAGE_SIZE                   (-5607)
     2357/** Process Verficiation Failure: Bad new-header offset in the MZ header. */
     2358#define VERR_SUP_VP_BAD_MZ_OFFSET                    (-5608)
     2359/** Process Verficiation Failure: Bad optional header field. */
     2360#define VERR_SUP_VP_BAD_OPTIONAL_HEADER              (-5609)
     2361/** Process Verficiation Failure: Bad section alignment value in image
     2362 *  header. */
     2363#define VERR_SUP_VP_BAD_SECTION_ALIGNMENT_VALUE      (-5610)
     2364/** Process Verficiation Failure: Bad section raw data size. */
     2365#define VERR_SUP_VP_BAD_SECTION_FILE_SIZE            (-5611)
     2366/** Process Verficiation Failure: Bad virtual section address. */
     2367#define VERR_SUP_VP_BAD_SECTION_RVA                  (-5612)
     2368/** Process Verficiation Failure: Bad virtual section size. */
     2369#define VERR_SUP_VP_BAD_SECTION_VIRTUAL_SIZE         (-5613)
     2370/** Process Verficiation Failure: Bad size of image header. */
     2371#define VERR_SUP_VP_BAD_SIZE_OF_HEADERS              (-5614)
     2372/** Process Verficiation Failure: The process is being debugged. */
     2373#define VERR_SUP_VP_DEBUGGED                         (-5615)
     2374/** Process Verficiation Failure: A DLL was found more than once. */
     2375#define VERR_SUP_VP_DUPLICATE_DLL_MAPPING            (-5616)
     2376/** Process Verficiation Failure: Image section region is too large. */
     2377#define VERR_SUP_VP_EMPTY_REGION_TOO_LARGE           (-5617)
     2378/** Process Verficiation Failure: Exectuable file name and process image name
     2379 *  does not match up. */
     2380#define VERR_SUP_VP_EXE_VS_PROC_NAME_MISMATCH        (-5618)
     2381/** Process Verficiation Failure: Found executable memory allocated in the
     2382 *  process.  There is only supposed be executable memory associated with
     2383 *  image file mappings (DLLs & EXE). */
     2384#define VERR_SUP_VP_FOUND_EXEC_MEMORY                (-5619)
     2385/** Process Verficiation Failure: There is more than one known executable mapped
     2386 *  into the process. */
     2387#define VERR_SUP_VP_FOUND_MORE_THAN_ONE_EXE_MAPPING  (-5620)
     2388/** Process Verficiation Failure: Error closing image file handle. */
     2389#define VERR_SUP_VP_IMAGE_FILE_CLOSE_ERROR           (-5621)
     2390/** Process Verficiation Failure: Error opening image file. */
     2391#define VERR_SUP_VP_IMAGE_FILE_OPEN_ERROR            (-5622)
     2392/** Process Verficiation Failure: Error reading image file header. */
     2393#define VERR_SUP_VP_IMAGE_HDR_READ_ERROR             (-5623)
     2394/** Process Verficiation Failure: Image mapping is bogus as the first region
     2395 *  has different AllocationBase and BaseAddress values, indicating that a
     2396 *  section was unmapped or otherwise tampered with. */
     2397#define VERR_SUP_VP_IMAGE_MAPPING_BASE_ERROR         (-5624)
     2398/** Process Verficiation Failure: Error reading process memory for comparing
     2399 *  with disk data. */
     2400#define VERR_SUP_VP_MEMORY_READ_ERROR                (-5625)
     2401/** Process Verficiation Failure: Found no executable mapped into the process
     2402 *  address space. */
     2403#define VERR_SUP_VP_NO_FOUND_NO_EXE_MAPPING          (-5626)
     2404/** Process Verficiation Failure: An image mapping failed to report a name. */
     2405#define VERR_SUP_VP_NO_IMAGE_MAPPING_NAME            (-5627)
     2406/** Process Verficiation Failure: No KERNE32.DLL mapping found.  This is
     2407 *  impossible. */
     2408#define VERR_SUP_VP_NO_KERNEL32_MAPPING              (-5628)
     2409/** Process Verficiation Failure: Error allocating memory. */
     2410#define VERR_SUP_VP_NO_MEMORY                        (-5629)
     2411/** Process Verficiation Failure: Erorr allocating state memory or querying
     2412 *  the system32 path. */
     2413#define VERR_SUP_VP_NO_MEMORY_STATE                  (-5630)
     2414/** Process Verficiation Failure: No NTDLL.DLL mapping found.  This is
     2415 *  impossible. */
     2416#define VERR_SUP_VP_NO_NTDLL_MAPPING                 (-5631)
     2417/** Process Verficiation Failure: A DLL residing outside System32 was found
     2418 *  in the process. */
     2419#define VERR_SUP_VP_NON_SYSTEM32_DLL                 (-5632)
     2420/** Process Verficiation Failure: An unknown and unwanted DLL was found loaded
     2421 *  into the process. */
     2422#define VERR_SUP_VP_NOT_KNOWN_DLL_OR_EXE             (-5633)
     2423/** Process Verficiation Failure: The name of an image file changes between
     2424 *  mapping regions. */
     2425#define VERR_SUP_VP_NT_MAPPING_NAME_CHANGED          (-5634)
     2426/** Process Verficiation Failure: Error querying process name. */
     2427#define VERR_SUP_VP_NT_QI_PROCESS_NM_ERROR           (-5635)
     2428/** Process Verficiation Failure: Error querying thread information. */
     2429#define VERR_SUP_VP_NT_QI_THREAD_ERROR               (-5636)
     2430/** Process Verficiation Failure: Error query virtual memory information. */
     2431#define VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_ERROR       (-5637)
     2432/** Process Verficiation Failure: Error query virtual memory mapping name. */
     2433#define VERR_SUP_VP_NT_QI_VIRTUAL_MEMORY_NM_ERROR    (-5638)
     2434/** Process Verficiation Failure: Error determining the full path of
     2435 *  System32. */
     2436#define VERR_SUP_VP_SYSTEM32_PATH                    (-5639)
     2437/** Process Verficiation Failure: The process has more than one thread. */
     2438#define VERR_SUP_VP_THREAD_NOT_ALONE                 (-5640)
     2439/** Process Verficiation Failure: The image mapping is too large (>= 2GB). */
     2440#define VERR_SUP_VP_TOO_HIGH_REGION_RVA              (-5641)
     2441/** Process Verficiation Failure: The memory region is too large (>= 2GB). */
     2442#define VERR_SUP_VP_TOO_LARGE_REGION                 (-5642)
     2443/** Process Verficiation Failure: There are too many DLLs loaded. */
     2444#define VERR_SUP_VP_TOO_MANY_DLLS_LOADED             (-5643)
     2445/** Process Verficiation Failure: An image has too many regions. */
     2446#define VERR_SUP_VP_TOO_MANY_IMAGE_REGIONS           (-5644)
     2447/** Process Verficiation Failure: The process has too many virtual memory
     2448 *  regions. */
     2449#define VERR_SUP_VP_TOO_MANY_MEMORY_REGIONS          (-5645)
     2450/** Process Verficiation Failure: An image has too many sections. */
     2451#define VERR_SUP_VP_TOO_MANY_SECTIONS                (-5646)
     2452/** Process Verficiation Failure: An image is targetting an unexpected
     2453 *  machine/CPU. */
     2454#define VERR_SUP_VP_UNEXPECTED_IMAGE_MACHINE         (-5647)
     2455/** Process Verficiation Failure: Unexpected section protection flag
     2456 *  combination. */
     2457#define VERR_SUP_VP_UNEXPECTED_SECTION_FLAGS         (-5648)
     2458/** Process Verficiation Failure: Expected the process and exe to have forced
     2459 * integrity checking enabled (verifying signatures). */
     2460#define VERR_SUP_VP_EXE_MISSING_FORCE_INTEGRITY     (-5649)
     2461/** Process Verficiation Failure: Expected the process and exe to have dynamic
     2462 * base enabled. */
     2463#define VERR_SUP_VP_EXE_MISSING_DYNAMIC_BASE        (-5650)
     2464/** Process Verficiation Failure: Expected the process and exe to advertise
     2465 * NX compatibility. */
     2466#define VERR_SUP_VP_EXE_MISSING_NX_COMPAT           (-5651)
     2467/** Process Verficiation Failure: The DllCharacteristics of the process
     2468 * does not match the value in the optional header in the exe file. */
     2469#define VERR_SUP_VP_DLL_CHARECTERISTICS_MISMATCH    (-5652)
     2470/** Process Verficiation Failure: The ImageCharacteristics of the process
     2471 * does not match the value in the file header in the exe file. */
     2472#define VERR_SUP_VP_IMAGE_CHARECTERISTICS_MISMATCH  (-5653)
     2473/** Process Verficiation Failure: Error querying image information. */
     2474#define VERR_SUP_VP_NT_QI_PROCESS_IMG_INFO_ERROR    (-5654)
     2475/** Process Verficiation Failure: Error querying debug port. */
     2476#define VERR_SUP_VP_NT_QI_PROCESS_DBG_PORT_ERROR    (-5655)
     2477/** WinVerifyTrust failed with an unexpected status code when using the
     2478 * catalog-file approach. */
     2479#define VERR_SUP_VP_WINTRUST_CAT_FAILURE            (-5656)
     2480/** The image is required to be signed with the same certificate as the rest
     2481 * of VirtualBox. */
     2482#define VERR_SUP_VP_NOT_SIGNED_WITH_BUILD_CERT      (-5657)
     2483/** Internal processing error: Not build certificate. */
     2484#define VERR_SUP_VP_NOT_BUILD_CERT_IPE              (-5658)
     2485/** The image requires to be signed using the kernel-code signing process. */
     2486#define VERR_SUP_VP_NOT_VALID_KERNEL_CODE_SIGNATURE (-5659)
     2487/** Unexpected number of valid paths. */
     2488#define VERR_SUP_VP_UNEXPECTED_VALID_PATH_COUNT     (-5660)
     2489/** The image is required to force integrity checks. */
     2490#define VERR_SUP_VP_SIGNATURE_CHECKS_NOT_ENFORCED   (-5661)
     2491
     2492/** @} */
     2493
    23132494/** @name VBox Extension Pack Status Codes
    23142495 * @{
  • trunk/include/VBox/sup.h

    r49965 r51770  
    724724    /** IPRT init related. */
    725725    kSupInitOp_IPRT,
     726    /** Miscellaneous. */
     727    kSupInitOp_Misc,
    726728    /** Place holder. */
    727729    kSupInitOp_End
     
    18481850
    18491851
     1852/** @name Trust Anchors and Certificates
     1853 * @{ */
     1854
     1855/**
     1856 * Trust anchor table entry (in generated Certificates.cpp).
     1857 */
     1858typedef struct SUPTAENTRY
     1859{
     1860    /** Pointer to the raw bytes. */
     1861    const unsigned char    *pch;
     1862    /** Number of bytes. */
     1863    unsigned                cb;
     1864} SUPTAENTRY;
     1865/** Pointer to a trust anchor table entry. */
     1866typedef SUPTAENTRY const *PCSUPTAENTRY;
     1867
     1868/** Macro for simplifying generating the trust anchor tables. */
     1869#define SUPTAENTRY_GEN(a_abTA)      { &a_abTA[0], sizeof(a_abTA) }
     1870
     1871/** All certificates we know. */
     1872extern SUPTAENTRY const             g_aSUPAllTAs[];
     1873/** Number of entries in g_aSUPAllTAs. */
     1874extern unsigned const               g_cSUPAllTAs;
     1875
     1876/** Software publisher certificate roots (Authenticode). */
     1877extern SUPTAENTRY const             g_aSUPSpcRootTAs[];
     1878/** Number of entries in g_aSUPSpcRootTAs. */
     1879extern unsigned const               g_cSUPSpcRootTAs;
     1880
     1881/** Kernel root certificates used by Windows. */
     1882extern SUPTAENTRY const             g_aSUPNtKernelRootTAs[];
     1883/** Number of entries in g_aSUPNtKernelRootTAs. */
     1884extern unsigned const               g_cSUPNtKernelRootTAs;
     1885
     1886/** Timestamp root certificates trusted by Windows. */
     1887extern SUPTAENTRY const             g_aSUPTimestampTAs[];
     1888/** Number of entries in g_aSUPTimestampTAs. */
     1889extern unsigned const               g_cSUPTimestampTAs;
     1890
     1891/** TAs we trust (the build certificate, Oracle VirtualBox). */
     1892extern SUPTAENTRY const             g_aSUPTrustedTAs[];
     1893/** Number of entries in g_aSUPTrustedTAs. */
     1894extern unsigned const               g_cSUPTrustedTAs;
     1895
     1896/** Supplemental certificates, like cross signing certificates. */
     1897extern SUPTAENTRY const             g_aSUPSupplementalTAs[];
     1898/** Number of entries in g_aSUPTrustedTAs. */
     1899extern unsigned const               g_cSUPSupplementalTAs;
     1900
     1901/** The build certificate. */
     1902extern const unsigned char          g_abSUPBuildCert[];
     1903/** The size of the build certificate. */
     1904extern const unsigned               g_cbSUPBuildCert;
     1905
    18501906/** @} */
    18511907
     1908
     1909/** @} */
     1910
    18521911RT_C_DECLS_END
    18531912
  • trunk/include/iprt/asm-math.h

    r29257 r51770  
    2929#include <iprt/types.h>
    3030
     31#if defined(_MSC_VER) && RT_INLINE_ASM_USES_INTRIN
     32# include <intrin.h>
     33  /* Emit the intrinsics at all optimization levels. */
     34# pragma intrinsic(__emul)
     35# pragma intrinsic(__emulu)
     36# ifdef RT_ARCH_AMD64
     37#  pragma intrinsic(_mul128)
     38#  pragma intrinsic(_umul128)
     39# endif
     40#endif
     41
    3142
    3243/** @defgroup grp_rt_asm_math   Interger Math Optimizations
     
    3950 * @returns u32F1 * u32F2.
    4051 */
    41 #if RT_INLINE_ASM_EXTERNAL && defined(RT_ARCH_X86)
     52
     53#if RT_INLINE_ASM_EXTERNAL && !RT_INLINE_ASM_USES_INTRIN && defined(RT_ARCH_X86)
    4254DECLASM(uint64_t) ASMMult2xU32RetU64(uint32_t u32F1, uint32_t u32F2);
    4355#else
     
    5062                         : "=A" (u64)
    5163                         : "a" (u32F2), "d" (u32F1));
     64#  elif RT_INLINE_ASM_USES_INTRIN
     65    u64 = __emulu(u32F1, u32F2);
    5266#  else
    5367    __asm
     
    7387 * @returns u32F1 * u32F2.
    7488 */
    75 #if RT_INLINE_ASM_EXTERNAL && defined(RT_ARCH_X86)
     89#if RT_INLINE_ASM_EXTERNAL && !RT_INLINE_ASM_USES_INTRIN && defined(RT_ARCH_X86)
    7690DECLASM(int64_t) ASMMult2xS32RetS64(int32_t i32F1, int32_t i32F2);
    7791#else
     
    8498                         : "=A" (i64)
    8599                         : "a" (i32F2), "d" (i32F1));
     100#  elif RT_INLINE_ASM_USES_INTRIN
     101    i64 = __emul(i32F1, i32F2);
    86102#  else
    87103    __asm
     
    100116}
    101117#endif
     118
     119
     120#if ARCH_BITS == 64
     121DECLINLINE(uint64_t) ASMMult2xU64Ret2xU64(uint64_t u64F1, uint64_t u64F2, uint64_t *pu64ProdHi)
     122{
     123# if defined(RT_ARCH_AMD64) && (RT_INLINE_ASM_GNU_STYLE || RT_INLINE_ASM_USES_INTRIN)
     124#  if RT_INLINE_ASM_GNU_STYLE
     125    uint64_t u64Low, u64High;
     126    __asm__ __volatile__("mull %%rdx"
     127                         : "=a" (u64Low), "=d" (u64High)
     128                         : "0" (u64F1), "1" (u64F2));
     129    *pu64ProdHi = u64High;
     130    return u64Low;
     131#  elif RT_INLINE_ASM_USES_INTRIN
     132    return _umul128(u64F1, u64F2, pu64ProdHi);
     133#  else
     134#   error "hmm"
     135#  endif
     136# else  /* generic: */
     137    /*
     138     *   F1 * F2 = Prod
     139     *   --   --
     140     *   ab * cd =  b*d + a*d*10  +  b*c*10 + a*c*100
     141     *
     142     * Where a, b, c and d are 'digits', and 10 is max digit + 1.
     143     *
     144     * Our digits are 32-bit wide, so instead of 10 we multiply by 4G.
     145     *  Prod = F1.s.Lo*F2.s.Lo    + F1.s.Hi*F2.s.Lo*4G
     146     *       + F1.s.Lo*F2.s.Hi*4G + F1.s.Hi*F2.s.Hi*4G*4G
     147     */
     148    RTUINT128U Prod;
     149    RTUINT64U  Tmp1;
     150    uint64_t   u64Tmp;
     151    RTUINT64U  F1, F2;
     152    F1.u = u64F1;
     153    F2.u = u64F2;
     154
     155    Prod.s.Lo = ASMMult2xU32RetU64(F1.s.Lo, F2.s.Lo);
     156
     157    Tmp1.u = ASMMult2xU32RetU64(F1.s.Hi, F2.s.Lo);
     158    u64Tmp = (uint64_t)Prod.DWords.dw1 + Tmp1.s.Lo;
     159    Prod.DWords.dw1 = (uint32_t)u64Tmp;
     160    Prod.s.Hi = Tmp1.s.Hi;
     161    Prod.s.Hi += u64Tmp >> 32; /* carry */
     162
     163    Tmp1.u = ASMMult2xU32RetU64(F1.s.Lo, F2.s.Hi);
     164    u64Tmp = (uint64_t)Prod.DWords.dw1 + Tmp1.s.Lo;
     165    Prod.DWords.dw1 = (uint32_t)u64Tmp;
     166    u64Tmp >>= 32;      /* carry */
     167    u64Tmp += Prod.DWords.dw2;
     168    u64Tmp += Tmp1.s.Hi;
     169    Prod.DWords.dw2 = (uint32_t)u64Tmp;
     170    Prod.DWords.dw3 += u64Tmp >> 32; /* carry */
     171
     172    Prod.s.Hi += ASMMult2xU32RetU64(F1.s.Hi, F2.s.Hi);
     173    *pu64ProdHi  = Prod.s.Hi;
     174    return Prod.s.Lo;
     175# endif
     176}
     177#endif
     178
    102179
    103180
  • trunk/include/iprt/base64.h

    r44529 r51770  
    4949 * @returns The length in bytes. -1 if the encoding is bad.
    5050 *
    51  * @param   pszString           The Base64 encoded string.
    52  * @param   ppszEnd             If not NULL, this will point to the first char
    53  *                              following the Base64 encoded text block. If
    54  *                              NULL the entire string is assumed to be Base64.
     51 * @param   pszString       The Base64 encoded string.
     52 * @param   ppszEnd         If not NULL, this will point to the first char
     53 *                          following the Base64 encoded text block. If
     54 *                          NULL the entire string is assumed to be Base64.
    5555 */
    5656RTDECL(ssize_t) RTBase64DecodedSize(const char *pszString, char **ppszEnd);
     57
     58/**
     59 * Calculates the decoded data size for a Base64 encoded string.
     60 *
     61 * @returns The length in bytes. -1 if the encoding is bad.
     62 *
     63 * @param   pszString       The Base64 encoded string.
     64 * @param   cchStringMax    The max length to decode, use RTSTR_MAX if the
     65 *                          length of @a pszString is not known and it is
     66 *                          really zero terminated.
     67 * @param   ppszEnd         If not NULL, this will point to the first char
     68 *                          following the Base64 encoded text block. If
     69 *                          NULL the entire string is assumed to be Base64.
     70 */
     71RTDECL(ssize_t) RTBase64DecodedSizeEx(const char *pszString, size_t cchStringMax, char **ppszEnd);
    5772
    5873/**
     
    7893 */
    7994RTDECL(int) RTBase64Decode(const char *pszString, void *pvData, size_t cbData, size_t *pcbActual, char **ppszEnd);
     95
     96/**
     97 * Decodes a Base64 encoded string into the buffer supplied by the caller.
     98 *
     99 * @returns IPRT status code.
     100 * @retval  VERR_BUFFER_OVERFLOW if the buffer is too small. pcbActual will not
     101 *          be set, nor will ppszEnd.
     102 * @retval  VERR_INVALID_BASE64_ENCODING if the encoding is wrong.
     103 *
     104 * @param   pszString       The Base64 string. Whether the entire string or
     105 *                          just the start of the string is in Base64 depends
     106 *                          on whether ppszEnd is specified or not.
     107 * @param   cchStringMax    The max length to decode, use RTSTR_MAX if the
     108 *                          length of @a pszString is not known and it is
     109 *                          really zero terminated.
     110 * @param   pvData          Where to store the decoded data.
     111 * @param   cbData          The size of the output buffer that pvData points to.
     112 * @param   pcbActual       Where to store the actual number of bytes returned.
     113 *                          Optional.
     114 * @param   ppszEnd         Indicates that the string may contain other stuff
     115 *                          after the Base64 encoded data when not NULL. Will
     116 *                          be set to point to the first char that's not part of
     117 *                          the encoding. If NULL the entire string must be part
     118 *                          of the Base64 encoded data.
     119 */
     120RTDECL(int) RTBase64DecodeEx(const char *pszString, size_t cchStringMax, void *pvData, size_t cbData,
     121                             size_t *pcbActual, char **ppszEnd);
    80122
    81123/**
  • trunk/include/iprt/cdefs.h

    r49766 r51770  
    12461246 * Runtime Library export or import declaration.
    12471247 * Data declared using this macro exists in all contexts.
    1248  * @param   type    The return type of the function declaration.
     1248 * @param   type    The data type.
     1249 */
     1250/** @def RT_DECL_DATA_CONST(type)
     1251 * Definition of a const variable. See DECL_HIDDEN_CONST.
     1252 * @param   type    The const data type.
    12491253 */
    12501254#if defined(IN_RT_R3) || defined(IN_RT_RC) || defined(IN_RT_R0)
    12511255# ifdef IN_RT_STATIC
    1252 #  define RTDATADECL(type)  DECLHIDDEN(type)
     1256#  define RTDATADECL(type)          DECLHIDDEN(type)
     1257#  define RT_DECL_DATA_CONST(type)  DECL_HIDDEN_CONST(type)
    12531258# else
    1254 #  define RTDATADECL(type)  DECLEXPORT(type)
    1255 # endif
    1256 #else
    1257 # define RTDATADECL(type)   DECLIMPORT(type)
     1259#  define RTDATADECL(type)          DECLEXPORT(type)
     1260#  if defined(__cplusplus) && defined(__GNUC__)
     1261#   define RT_DECL_DATA_CONST(type) type
     1262#  else
     1263#   define RT_DECL_DATA_CONST(type) DECLEXPORT(type)
     1264#  endif
     1265# endif
     1266#else
     1267# define RTDATADECL(type)           DECLIMPORT(type)
     1268# define RT_DECL_DATA_CONST(type)   DECLIMPORT(type)
    12581269#endif
    12591270
  • trunk/include/iprt/err.h

    r51766 r51770  
    438438 * Initialize a static error info structure.
    439439 *
     440 * @returns Pointer to the core error info structure.
    440441 * @param   pStaticErrInfo      The static error info structure to init.
    441442 */
    442 DECLINLINE(void) RTErrInfoInitStatic(PRTERRINFOSTATIC pStaticErrInfo)
     443DECLINLINE(PRTERRINFO) RTErrInfoInitStatic(PRTERRINFOSTATIC pStaticErrInfo)
    443444{
    444445    RTErrInfoInit(&pStaticErrInfo->Core, pStaticErrInfo->szMsg, sizeof(pStaticErrInfo->szMsg));
    445446    pStaticErrInfo->Core.fFlags = RTERRINFO_FLAGS_T_STATIC | RTERRINFO_FLAGS_MAGIC;
     447    return &pStaticErrInfo->Core;
    446448}
    447449
     
    511513 */
    512514RTDECL(int)         RTErrInfoSetV(PRTERRINFO pErrInfo, int rc, const char *pszFormat, va_list va);
     515
     516/**
     517 * Adds more error info details.
     518 *
     519 * @returns @a rc.
     520 *
     521 * @param   pErrInfo            The error info structure to fill in.
     522 * @param   rc                  The status code to return.
     523 * @param   pszMsg              The error message string to add.
     524 */
     525RTDECL(int)         RTErrInfoAdd(PRTERRINFO pErrInfo, int rc, const char *pszMsg);
     526
     527/**
     528 * Adds more error info details, with a sprintf style message.
     529 *
     530 * @returns @a rc.
     531 *
     532 * @param   pErrInfo            The error info structure to fill in.
     533 * @param   rc                  The status code to return.
     534 * @param   pszFormat           The format string to add.
     535 * @param   ...                 The format arguments.
     536 */
     537RTDECL(int)         RTErrInfoAddF(PRTERRINFO pErrInfo, int rc, const char *pszFormat, ...);
     538
     539/**
     540 * Adds more error info details, with a vsprintf style message.
     541 *
     542 * @returns @a rc.
     543 *
     544 * @param   pErrInfo            The error info structure to fill in.
     545 * @param   rc                  The status code to return.
     546 * @param   pszFormat           The format string to add.
     547 * @param   va                  The format arguments.
     548 */
     549RTDECL(int)         RTErrInfoAddV(PRTERRINFO pErrInfo, int rc, const char *pszFormat, va_list va);
    513550
    514551/**
     
    19231960/** @} */
    19241961
     1962/** @name RTAsn1 status codes
     1963 * @{ */
     1964/** Temporary place holder.  */
     1965#define VERR_ASN1_ERROR                             (-22800)
     1966/** Encountered an ASN.1 string type that is not supported. */
     1967#define VERR_ASN1_STRING_TYPE_NOT_IMPLEMENTED       (-22801)
     1968/** Invalid ASN.1 UTF-8 STRING encoding. */
     1969#define VERR_ASN1_INVALID_UTF8_STRING_ENCODING      (-22802)
     1970/** Invalid ASN.1 NUMERIC STRING encoding. */
     1971#define VERR_ASN1_INVALID_NUMERIC_STRING_ENCODING   (-22803)
     1972/** Invalid ASN.1 PRINTABLE STRING encoding. */
     1973#define VERR_ASN1_INVALID_PRINTABLE_STRING_ENCODING (-22804)
     1974/** Invalid ASN.1 T61/TELETEX STRING encoding. */
     1975#define VERR_ASN1_INVALID_T61_STRING_ENCODING       (-22805)
     1976/** Invalid ASN.1 VIDEOTEX STRING encoding. */
     1977#define VERR_ASN1_INVALID_VIDEOTEX_STRING_ENCODING  (-22806)
     1978/** Invalid ASN.1 IA5 STRING encoding. */
     1979#define VERR_ASN1_INVALID_IA5_STRING_ENCODING       (-22807)
     1980/** Invalid ASN.1 GRAPHIC STRING encoding. */
     1981#define VERR_ASN1_INVALID_GRAPHIC_STRING_ENCODING   (-22808)
     1982/** Invalid ASN.1 ISO-646/VISIBLE STRING encoding. */
     1983#define VERR_ASN1_INVALID_VISIBLE_STRING_ENCODING   (-22809)
     1984/** Invalid ASN.1 GENERAL STRING encoding. */
     1985#define VERR_ASN1_INVALID_GENERAL_STRING_ENCODING   (-22810)
     1986/** Invalid ASN.1 UNIVERSAL STRING encoding. */
     1987#define VERR_ASN1_INVALID_UNIVERSAL_STRING_ENCODING (-22811)
     1988/** Invalid ASN.1 BMP STRING encoding. */
     1989#define VERR_ASN1_INVALID_BMP_STRING_ENCODING       (-22812)
     1990/** Invalid ASN.1 OBJECT IDENTIFIER encoding. */
     1991#define VERR_ASN1_INVALID_OBJID_ENCODING            (-22813)
     1992/** A component value of an ASN.1 OBJECT IDENTIFIER is too big for our
     1993 * internal representation (32-bits). */
     1994#define VERR_ASN1_OBJID_COMPONENT_TOO_BIG           (-22814)
     1995/** Too many components in an ASN.1 OBJECT IDENTIFIER for our internal
     1996 * representation. */
     1997#define VERR_ASN1_OBJID_TOO_MANY_COMPONENTS         (-22815)
     1998/** The dotted-string representation of an ASN.1 OBJECT IDENTIFIER would be too
     1999 * long for our internal representation. */
     2000#define VERR_ASN1_OBJID_TOO_LONG_STRING_FORM        (-22816)
     2001/** Invalid dotted string. */
     2002#define VERR_ASN1_OBJID_INVALID_DOTTED_STRING       (-22817)
     2003/** Constructed string type not implemented. */
     2004#define VERR_ASN1_CONSTRUCTED_STRING_NOT_IMPL       (-22818)
     2005/** Expected a different string tag. */
     2006#define VERR_ASN1_STRING_TAG_MISMATCH               (-22819)
     2007/** Expected a different time tag. */
     2008#define VERR_ASN1_TIME_TAG_MISMATCH                 (-22820)
     2009/** More unconsumed data available. */
     2010#define VINF_ASN1_MORE_DATA                         (22821)
     2011/** RTAsnEncodeWriteHeader return code indicating that nothing was written
     2012 *  and the content should be skipped as well. */
     2013#define VINF_ASN1_NOT_ENCODED                       (22822)
     2014/** Unknown escape sequence encountered in TeletexString. */
     2015#define VERR_ASN1_TELETEX_UNKNOWN_ESC_SEQ           (-22823)
     2016/** Unsupported escape sequence encountered in TeletexString. */
     2017#define VERR_ASN1_TELETEX_UNSUPPORTED_ESC_SEQ       (-22824)
     2018/** Unsupported character set. */
     2019#define VERR_ASN1_TELETEX_UNSUPPORTED_CHARSET       (-22825)
     2020/** ASN.1 object has no virtual method table. */
     2021#define VERR_ASN1_NO_VTABLE                         (-22826)
     2022/** ASN.1 object has no pfnCheckSanity method.  */
     2023#define VERR_ASN1_NO_CHECK_SANITY_METHOD            (-22827)
     2024/** ASN.1 object is not present */
     2025#define VERR_ASN1_NOT_PRESENT                       (-22828)
     2026/** There are unconsumed bytes after decoding an ASN.1 object. */
     2027#define VERR_ASN1_CURSOR_NOT_AT_END                 (-22829)
     2028/** Long ASN.1 tag form is not implemented. */
     2029#define VERR_ASN1_CURSOR_LONG_TAG                   (-22830)
     2030/** Bad ASN.1 object length encoding. */
     2031#define VERR_ASN1_CURSOR_BAD_LENGTH_ENCODING        (-22831)
     2032/** Indefinite length form is against the rules. */
     2033#define VERR_ASN1_CURSOR_ILLEGAL_IDEFINITE_LENGTH   (-22832)
     2034/** Indefinite length form is not implemented. */
     2035#define VERR_ASN1_CURSOR_IDEFINITE_LENGTH_NOT_SUP   (-22833)
     2036/** ASN.1 object length goes beyond the end of the byte stream being decoded. */
     2037#define VERR_ASN1_CURSOR_BAD_LENGTH                 (-22834)
     2038/** Not more data in ASN.1 byte stream. */
     2039#define VERR_ASN1_CURSOR_NO_MORE_DATA               (-22835)
     2040/** Too little data in ASN.1 byte stream. */
     2041#define VERR_ASN1_CURSOR_TOO_LITTLE_DATA_LEFT       (-22836)
     2042/** Constructed string is not according to the encoding rules. */
     2043#define VERR_ASN1_CURSOR_ILLEGAL_CONSTRUCTED_STRING (-22837)
     2044/** Unexpected ASN.1 tag encountered while decoding. */
     2045#define VERR_ASN1_CURSOR_TAG_MISMATCH               (-22838)
     2046/** Unexpected ASN.1 tag class/flag encountered while decoding. */
     2047#define VERR_ASN1_CURSOR_TAG_FLAG_CLASS_MISMATCH    (-22839)
     2048/** ASN.1 bit string object is out of bounds. */
     2049#define VERR_ASN1_BITSTRING_OUT_OF_BOUNDS           (-22840)
     2050/** Bad ASN.1 time object. */
     2051#define VERR_ASN1_TIME_BAD_NORMALIZE_INPUT          (-22841)
     2052/** Failed to normalize ASN.1 time object. */
     2053#define VERR_ASN1_TIME_NORMALIZE_ERROR              (-22842)
     2054/** Normalization of ASN.1 time object didn't work out. */
     2055#define VERR_ASN1_TIME_NORMALIZE_MISMATCH           (-22843)
     2056/** Invalid ASN.1 UTC TIME encoding. */
     2057#define VERR_ASN1_INVALID_UTC_TIME_ENCODING         (-22844)
     2058/** Invalid ASN.1 GENERALIZED TIME encoding. */
     2059#define VERR_ASN1_INVALID_GENERALIZED_TIME_ENCODING (-22845)
     2060/** Invalid ASN.1 BOOLEAN encoding. */
     2061#define VERR_ASN1_INVALID_BOOLEAN_ENCODING          (-22846)
     2062/** Invalid ASN.1 NULL encoding. */
     2063#define VERR_ASN1_INVALID_NULL_ENCODING             (-22847)
     2064/** Invalid ASN.1 BIT STRING encoding. */
     2065#define VERR_ASN1_INVALID_BITSTRING_ENCODING        (-22848)
     2066/** Unimplemented ASN.1 tag reached the RTAsn1DynType code. */
     2067#define VERR_ASN1_DYNTYPE_TAG_NOT_IMPL              (-22849)
     2068/** ASN.1 tag and flags/class mismatch in RTAsn1DynType code. */
     2069#define VERR_ASN1_DYNTYPE_BAD_TAG                   (-22850)
     2070/** Unexpected ASN.1 fake/dummy object. */
     2071#define VERR_ASN1_DUMMY_OBJECT                      (-22851)
     2072/** ASN.1 object is too long. */
     2073#define VERR_ASN1_TOO_LONG                          (-22852)
     2074/** Expected primitive ASN.1 object. */
     2075#define VERR_ASN1_EXPECTED_PRIMITIVE                (-22853)
     2076/** Expected valid data pointer for ASN.1 object. */
     2077#define VERR_ASN1_INVALID_DATA_POINTER              (-22854)
     2078
     2079/** ANS.1 internal error 1. */
     2080#define VERR_ASN1_INTERNAL_ERROR_1                  (-22895)
     2081/** ANS.1 internal error 2. */
     2082#define VERR_ASN1_INTERNAL_ERROR_2                  (-22896)
     2083/** ANS.1 internal error 3. */
     2084#define VERR_ASN1_INTERNAL_ERROR_3                  (-22897)
     2085/** ANS.1 internal error 4. */
     2086#define VERR_ASN1_INTERNAL_ERROR_4                  (-22898)
     2087/** ANS.1 internal error 5. */
     2088#define VERR_ASN1_INTERNAL_ERROR_5                  (-22899)
     2089/** @} */
     2090
     2091/** @name More RTLdr status codes.
     2092 * @{ */
     2093/** Image Verficiation Failure: No Authenticode Signature. */
     2094#define VERR_LDRVI_NOT_SIGNED                       (-22900)
     2095/** Image Verficiation Warning: No Authenticode Signature, but on whitelist. */
     2096#define VINF_LDRVI_NOT_SIGNED                       (22900)
     2097/** Image Verficiation Failure: Error reading image headers.  */
     2098#define VERR_LDRVI_READ_ERROR_HDR                   (-22901)
     2099/** Image Verficiation Failure: Error reading section headers. */
     2100#define VERR_LDRVI_READ_ERROR_SHDRS                 (-22902)
     2101/** Image Verficiation Failure: Error reading authenticode signature data. */
     2102#define VERR_LDRVI_READ_ERROR_SIGNATURE             (-22903)
     2103/** Image Verficiation Failure: Error reading file for hashing. */
     2104#define VERR_LDRVI_READ_ERROR_HASH                  (-22904)
     2105/** Image Verficiation Failure: Error determining the file length. */
     2106#define VERR_LDRVI_FILE_LENGTH_ERROR                (-22905)
     2107/** Image Verficiation Failure: Error allocating memory for state data. */
     2108#define VERR_LDRVI_NO_MEMORY_STATE                  (-22906)
     2109/** Image Verficiation Failure: Error allocating memory for authenticode
     2110 *  signature data. */
     2111#define VERR_LDRVI_NO_MEMORY_SIGNATURE              (-22907)
     2112/** Image Verficiation Failure: Error allocating memory for section headers. */
     2113#define VERR_LDRVI_NO_MEMORY_SHDRS                  (-22908)
     2114/** Image Verficiation Failure: Authenticode parsing output. */
     2115#define VERR_LDRVI_NO_MEMORY_PARSE_OUTPUT           (-22909)
     2116/** Image Verficiation Failure: Invalid security directory entry. */
     2117#define VERR_LDRVI_INVALID_SECURITY_DIR_ENTRY       (-22910)
     2118/** Image Verficiation Failure:  */
     2119#define VERR_LDRVI_BAD_CERT_HDR_LENGTH              (-22911)
     2120/** Image Verficiation Failure:  */
     2121#define VERR_LDRVI_BAD_CERT_HDR_REVISION            (-22912)
     2122/** Image Verficiation Failure:  */
     2123#define VERR_LDRVI_BAD_CERT_HDR_TYPE                (-22913)
     2124/** Image Verficiation Failure: More than one certificate table entry.  */
     2125#define VERR_LDRVI_BAD_CERT_MULTIPLE                (-22914)
     2126
     2127/** Image Verficiation Failure:  */
     2128#define VERR_LDRVI_BAD_MZ_OFFSET                    (-22915)
     2129/** Image Verficiation Failure: Invalid section count. */
     2130#define VERR_LDRVI_INVALID_SECTION_COUNT            (-22916)
     2131/** Image Verficiation Failure: Raw data offsets and sizes are out of range. */
     2132#define VERR_LDRVI_SECTION_RAW_DATA_VALUES          (-22917)
     2133/** Optional header magic and target machine does not match. */
     2134#define VERR_LDRVI_MACHINE_OPT_HDR_MAGIC_MISMATCH   (-22918)
     2135/** Unsupported image target architecture. */
     2136#define VERR_LDRVI_UNSUPPORTED_ARCH                 (-22919)
     2137
     2138/** Image Verification Failure: Internal error in signature parser. */
     2139#define VERR_LDRVI_PARSE_IPE                        (-22921)
     2140/** Generic BER parse error. Will be refined later. */
     2141#define VERR_LDRVI_PARSE_BER_ERROR                  (-22922)
     2142
     2143/** Expected the signed data content to be the object ID of
     2144 * SpcIndirectDataContent, found something else instead. */
     2145#define VERR_LDRVI_EXPECTED_INDIRECT_DATA_CONTENT_OID (-22923)
     2146/** Page hash table size overflow. */
     2147#define VERR_LDRVI_PAGE_HASH_TAB_SIZE_OVERFLOW      (-22924)
     2148/** Page hash table is too long (covers signature data, i.e. itself). */
     2149#define VERR_LDRVI_PAGE_HASH_TAB_TOO_LONG           (-22925)
     2150/** The page hash table is not strictly ordered by offset. */
     2151#define VERR_LDRVI_PAGE_HASH_TAB_NOT_STRICTLY_SORTED (-22926)
     2152/** The page hash table hashes data outside the defined and implict sections. */
     2153#define VERR_PAGE_HASH_TAB_HASHES_NON_SECTION_DATA  (-22927)
     2154/** Page hash mismatch. */
     2155#define VERR_LDRVI_PAGE_HASH_MISMATCH               (-22928)
     2156/** Image hash mismatch. */
     2157#define VERR_LDRVI_IMAGE_HASH_MISMATCH              (-22929)
     2158/** @} */
     2159
     2160/** @name RTCrX509 status codes.
     2161 * @{ */
     2162/** Generic X.509 error. */
     2163#define VERR_CR_X509_GENERIC_ERROR                  (-23000)
     2164/** Internal error in the X.509 code. */
     2165#define VERR_CR_X509_INTERNAL_ERROR                 (-23001)
     2166/** Internal error in the X.509 certificate path building and verification
     2167 * code. */
     2168#define VERR_CR_X509_CERTPATHS_INTERNAL_ERROR       (-23002)
     2169/** Path not verified yet. */
     2170#define VERR_CR_X509_NOT_VERIFIED                   (-23003)
     2171/** The certificate path has no trust anchor. */
     2172#define VERR_CR_X509_NO_TRUST_ANCHOR                (-23004)
     2173/** Unknown X.509 certificate signature algorithm. */
     2174#define VERR_CR_X509_UNKNOWN_CERT_SIGN_ALGO         (-23005)
     2175/** Certificate signature algorithm mismatch. */
     2176#define VERR_CR_X509_CERT_SIGN_ALGO_MISMATCH        (-23006)
     2177/** The signature algorithm in the to-be-signed certifcate part does not match
     2178 * the one assoicated with the signature. */
     2179#define VERR_CR_X509_CERT_TBS_SIGN_ALGO_MISMATCH    (-23007)
     2180/** Certificate extensions requires certificate version 3 or later.  */
     2181#define VERR_CR_X509_TBSCERT_EXTS_REQ_V3            (-23008)
     2182/** Unique issuer and subject IDs require version certificate 2. */
     2183#define VERR_CR_X509_TBSCERT_UNIQUE_IDS_REQ_V2      (-23009)
     2184/** Certificate serial number length is out of bounds. */
     2185#define VERR_CR_X509_TBSCERT_SERIAL_NUMBER_OUT_OF_BOUNDS (-23010)
     2186/** Unsupported X.509 certificate version. */
     2187#define VERR_CR_X509_TBSCERT_UNSUPPORTED_VERSION    (-23011)
     2188/** Public key is too small. */
     2189#define VERR_CR_X509_PUBLIC_KEY_TOO_SMALL           (-23012)
     2190/** Invalid strnig tag for a X.509 name object. */
     2191#define VERR_CR_X509_INVALID_NAME_STRING_TAG        (-23013)
     2192/** Empty string in X.509 name object. */
     2193#define VERR_CR_X509_NAME_EMPTY_STRING              (-23014)
     2194/** Non-string object inside X.509 name object. */
     2195#define VERR_CR_X509_NAME_NOT_STRING                (-23015)
     2196/** Empty set inside X.509 name. */
     2197#define VERR_CR_X509_NAME_EMPTY_SET                 (-23016)
     2198/** Empty sub-string set inside X.509 name. */
     2199#define VERR_CR_X509_NAME_EMPTY_SUB_SET             (-23017)
     2200/** The NotBefore and NotAfter values of an X.509 Validity object seems to
     2201 * have been swapped around. */
     2202#define VERR_CR_X509_VALIDITY_SWAPPED               (-23018)
     2203/** Duplicate certificate extension. */
     2204#define VERR_CR_X509_TBSCERT_DUPLICATE_EXTENSION    (-23019)
     2205/** Missing relative distinguished name map entry. */
     2206#define VERR_CR_X509_NAME_MISSING_RDN_MAP_ENTRY     (-23020)
     2207/** Certificate path validator: No trusted certificate paths. */
     2208#define VERR_CR_X509_CPV_NO_TRUSTED_PATHS           (-23021)
     2209/** Certificate path validator: No valid certificate policy. */
     2210#define VERR_CR_X509_CPV_NO_VALID_POLICY            (-23022)
     2211/** Certificate path validator: Unknown critical certificate extension. */
     2212#define VERR_CR_X509_CPV_UNKNOWN_CRITICAL_EXTENSION (-23023)
     2213/** Certificate path validator: Intermediate certificate is missing the
     2214 *  KeyCertSign usage flag. */
     2215#define VERR_CR_X509_CPV_MISSING_KEY_CERT_SIGN      (-23024)
     2216/** Certificate path validator: Hit the max certificate path length before
     2217 *  reaching trust anchor. */
     2218#define VERR_CR_X509_CPV_MAX_PATH_LENGTH            (-23025)
     2219/** Certificate path validator: Intermediate certificate is not marked as a
     2220 *  certificate authority (CA). */
     2221#define VERR_CR_X509_CPV_NOT_CA_CERT                (-23026)
     2222/** Certificate path validator: Intermeidate certificate is not a version 3
     2223 *  certificate. */
     2224#define VERR_CR_X509_CPV_NOT_V3_CERT                (-23027)
     2225/** Certificate path validator: Invalid policy mapping (to/from anyPolicy). */
     2226#define VERR_CR_X509_CPV_INVALID_POLICY_MAPPING     (-23028)
     2227/** Certificate path validator: Name constraints permits no names. */
     2228#define VERR_CR_X509_CPV_NO_PERMITTED_NAMES         (-23029)
     2229/** Certificate path validator: Name constraints does not permits the
     2230 *  certificate name. */
     2231#define VERR_CR_X509_CPV_NAME_NOT_PERMITTED         (-23030)
     2232/** Certificate path validator: Name constraints does not permits the
     2233 *  alternative certificate name. */
     2234#define VERR_CR_X509_CPV_ALT_NAME_NOT_PERMITTED     (-23031)
     2235/** Certificate path validator: Intermediate certificate subject does not
     2236 *  match child issuer property. */
     2237#define VERR_CR_X509_CPV_ISSUER_MISMATCH            (-23032)
     2238/** Certificate path validator: The certificate is not valid at the
     2239 *  specificed time. */
     2240#define VERR_CR_X509_CPV_NOT_VALID_AT_TIME          (-23033)
     2241/** Certificate path validator: Unexpected choice found in general subtree
     2242 *  object (name constraints). */
     2243#define VERR_CR_X509_CPV_UNEXP_GENERAL_SUBTREE_CHOICE (-23034)
     2244/** Certificate path validator: Unexpected minimum value found in general
     2245 *  subtree object (name constraints). */
     2246#define VERR_CR_X509_CPV_UNEXP_GENERAL_SUBTREE_MIN  (-23035)
     2247/** Certificate path validator: Unexpected maximum value found in
     2248 *  general subtree object (name constraints). */
     2249#define VERR_CR_X509_CPV_UNEXP_GENERAL_SUBTREE_MAX  (-23036)
     2250/** Certificate path builder: Encountered bad certificate context. */
     2251#define VERR_CR_X509_CPB_BAD_CERT_CTX               (-23037)
     2252/** OpenSSL d2i_X509 failed. */
     2253#define VERR_CR_X509_OSSL_D2I_FAILED                (-23090)
     2254/** @} */
     2255
     2256/** @name RTCrPkcs7 status codes.
     2257 * @{ */
     2258/** Generic PKCS \#7 error. */
     2259#define VERR_CR_PKCS7_GENERIC_ERROR                             (-23300)
     2260/** Signed data verfication failed because there are zero signer infos. */
     2261#define VERR_CR_PKCS7_NO_SIGNER_INFOS                           (-23301)
     2262/** Signed data certificate not found. */
     2263#define VERR_CR_PKCS7_SIGNED_DATA_CERT_NOT_FOUND                (-23302)
     2264/** Signed data verification failed due to key usage issues. */
     2265#define VERR_CR_PKCS7_KEY_USAGE_MISMATCH                        (-23303)
     2266/** Signed data verification failed because of missing (or duplicate)
     2267 * authenticated content-type attribute. */
     2268#define VERR_CR_PKCS7_MISSING_CONTENT_TYPE_ATTRIB               (-23304)
     2269/** Signed data verification failed because of the authenticated content-type
     2270 *  attribute did not match. */
     2271#define VERR_CR_PKCS7_CONTENT_TYPE_ATTRIB_MISMATCH              (-23305)
     2272/** Signed data verification failed because of a malformed authenticated
     2273 *  content-type attribute. */
     2274#define VERR_CR_PKCS7_BAD_CONTENT_TYPE_ATTRIB                   (-23306)
     2275/** Signed data verification failed because of missing (or duplicate)
     2276 * authenticated message-digest attribute. */
     2277#define VERR_CR_PKCS7_MISSING_MESSAGE_DIGEST_ATTRIB             (-23307)
     2278/** Signed data verification failed because the authenticated message-digest
     2279 *  attribute did not match. */
     2280#define VERR_CR_PKCS7_MESSAGE_DIGEST_ATTRIB_MISMATCH            (-23308)
     2281/** Signed data verification failed because of a malformed authenticated
     2282 *  message-digest attribute. */
     2283#define VERR_CR_PKCS7_BAD_MESSAGE_DIGEST_ATTRIB                 (-23309)
     2284/** Signature verification failed. */
     2285#define VERR_CR_PKCS7_SIGNATURE_VERIFICATION_FAILED             (-23310)
     2286/** Internal PKCS \#7 error. */
     2287#define VERR_CR_PKCS7_INTERNAL_ERROR                            (-22311)
     2288/** OpenSSL d2i_PKCS7 failed. */
     2289#define VERR_CR_PKCS7_OSSL_D2I_FAILED                           (-22312)
     2290/** OpenSSL PKCS \#7 verification failed. */
     2291#define VERR_CR_PKCS7_OSSL_VERIFY_FAILED                        (-22313)
     2292/** Digest algorithm parameters are not supported by the PKCS \#7 code. */
     2293#define VERR_CR_PKCS7_DIGEST_PARAMS_NOT_IMPL                    (-22314)
     2294/** The digest algorithm of a signer info entry was not found in the list of
     2295 *  digest algorithms in the signed data. */
     2296#define VERR_CR_PKCS7_DIGEST_ALGO_NOT_FOUND_IN_LIST             (-22315)
     2297/** The PKCS \#7 content is not signed data. */
     2298#define VERR_CR_PKCS7_NOT_SIGNED_DATA                           (-22316)
     2299/** No digest algorithms listed in PKCS \#7 signed data. */
     2300#define VERR_CR_PKCS7_NO_DIGEST_ALGORITHMS                      (-22317)
     2301/** Too many digest algorithms used by PKCS \#7 signed data.  This is an
     2302 * internal limitation of the code that aims at saving kernel stack space. */
     2303#define VERR_CR_PKCS7_TOO_MANY_DIGEST_ALGORITHMS                (-22318)
     2304/** Error creating digest algorithm calculator. */
     2305#define VERR_CR_PKCS7_DIGEST_CREATE_ERROR                       (-22319)
     2306/** Error while calculating a digest for a PKCS \#7 verficiation operation. */
     2307#define VERR_CR_PKCS7_DIGEST_CALC_ERROR                         (-22320)
     2308/** Unsupported PKCS \#7 signed data version. */
     2309#define VERR_CR_PKCS7_SIGNED_DATA_VERSION                       (-22350)
     2310/** PKCS \#7 signed data has no digest algorithms listed. */
     2311#define VERR_CR_PKCS7_SIGNED_DATA_NO_DIGEST_ALGOS               (-22351)
     2312/** Unknown digest algorithm used by PKCS \#7 object. */
     2313#define VERR_CR_PKCS7_UNKNOWN_DIGEST_ALGORITHM                  (-22352)
     2314/** Expected PKCS \#7 object to ship at least one certificate. */
     2315#define VERR_CR_PKCS7_NO_CERTIFICATES                           (-22353)
     2316/** Expected PKCS \#7 object to not contain any CRLs. */
     2317#define VERR_CR_PKCS7_EXPECTED_NO_CRLS                          (-22354)
     2318/** Expected PKCS \#7 object to contain exactly on signer info entry. */
     2319#define VERR_CR_PKCS7_EXPECTED_ONE_SIGNER_INFO                  (-22355)
     2320/** Unsupported PKCS \#7 signer info version. */
     2321#define VERR_CR_PKCS7_SIGNER_INFO_VERSION                       (-22356)
     2322/** PKCS \#7 singer info contains no issuer serial number. */
     2323#define VERR_CR_PKCS7_SIGNER_INFO_NO_ISSUER_SERIAL_NO           (-22357)
     2324/** Expected PKCS \#7 object to ship the signer certificate(s). */
     2325#define VERR_CR_PKCS7_SIGNER_CERT_NOT_SHIPPED                   (-22358)
     2326/** The encrypted digest algorithm does not match the one in the certificate. */
     2327#define VERR_CR_PKCS7_SIGNER_INFO_DIGEST_ENCRYPT_MISMATCH       (-22359)
     2328/** @} */
     2329
     2330/** @name RTCrSpc status codes.
     2331 * @{ */
     2332/** Generic SPC error. */
     2333#define VERR_CR_SPC_GENERIC_ERROR                               (-23400)
     2334/** SPC requires there to be exactly one SignerInfo entry. */
     2335#define VERR_CR_SPC_NOT_EXACTLY_ONE_SIGNER_INFOS                (-23401)
     2336/** There shall be exactly one digest algorithm to go with the single
     2337 *  SingerInfo entry required by SPC. */
     2338#define VERR_CR_SPC_NOT_EXACTLY_ONE_DIGEST_ALGO                 (-23402)
     2339/** The digest algorithm in the SignerInfo does not match the one in the
     2340 *  indirect data. */
     2341#define VERR_CR_SPC_SIGNED_IND_DATA_DIGEST_ALGO_MISMATCH        (-23403)
     2342/** The digest algorithm in the indirect data was not found in the list of
     2343 * digest algorithms in the signed data structure. */
     2344#define VERR_CR_SPC_IND_DATA_DIGEST_ALGO_NOT_IN_DIGEST_ALGOS    (-23404)
     2345/** The digest algorithm is not known to us. */
     2346#define VERR_CR_SPC_UNKNOWN_DIGEST_ALGO                         (-23405)
     2347/** The indirect data digest size does not match the digest algorithm. */
     2348#define VERR_CR_SPC_IND_DATA_DIGEST_SIZE_MISMATCH               (-23406)
     2349/** Exptected PE image data inside indirect data object. */
     2350#define VERR_CR_SPC_EXPECTED_PE_IMAGE_DATA                      (-23407)
     2351/** Internal SPC error: The PE image data is missing.  */
     2352#define VERR_CR_SPC_PEIMAGE_DATA_NOT_PRESENT                    (-23408)
     2353/** Bad SPC object moniker UUID field. */
     2354#define VERR_CR_SPC_BAD_MONIKER_UUID                            (-23409)
     2355/** Unknown SPC object moniker UUID. */
     2356#define VERR_CR_SPC_UNKNOWN_MONIKER_UUID                        (-23410)
     2357/** Internal SPC error: Bad object monker choice value. */
     2358#define VERR_CR_SPC_BAD_MONIKER_CHOICE                          (-23411)
     2359/** Internal SPC error: Bad object moniker data pointer. */
     2360#define VERR_CR_SPC_MONIKER_BAD_DATA                            (-23412)
     2361/** Multiple v2 PE image page hash tables. */
     2362#define VERR_CR_SPC_PEIMAGE_MULTIPLE_V2_HASH_TABS               (-23413)
     2363/** Version 1 PE image page hash tables has not been implemented/tested. */
     2364#define VERR_CR_SPC_PEIMAGE_V1_HASH_TABS_NOT_IMPL               (-23414)
     2365/** Unknown SPC PE image attribute. */
     2366#define VERR_CR_SPC_PEIMAGE_UNKNOWN_ATTRIBUTE                   (-23415)
     2367/** URL not expected in SPC PE image data. */
     2368#define VERR_CR_SPC_PEIMAGE_URL_UNEXPECTED                      (-23416)
     2369/** PE image data without any valid content was not expected. */
     2370#define VERR_CR_SPC_PEIMAGE_NO_CONTENT                          (-23417)
     2371/** @} */
     2372
     2373/** @name RTCrPkix status codes.
     2374 * @{ */
     2375/** Generic PKCS \#7 error. */
     2376#define VERR_CR_PKIX_GENERIC_ERROR                  (-23500)
     2377/** Parameters was presented to a signature schema that does not take any. */
     2378#define VERR_CR_PKIX_SIGNATURE_TAKES_NO_PARAMETERS  (-23501)
     2379/** Unknown hash digest type. */
     2380#define VERR_CR_PKIX_UNKNOWN_DIGEST_TYPE            (-23502)
     2381/** Internal error. */
     2382#define VERR_CR_PKIX_INTERNAL_ERROR                 (-23503)
     2383/** The hash is too long for the key used when signing/verifying. */
     2384#define VERR_CR_PKIX_HASH_TOO_LONG_FOR_KEY          (-23504)
     2385/** The signature is too long for the scratch buffer. */
     2386#define VERR_CR_PKIX_SIGNATURE_TOO_LONG             (-23505)
     2387/** The signature is greater than or equal to the key. */
     2388#define VERR_CR_PKIX_SIGNATURE_GE_KEY               (-23506)
     2389/** The signature is negative. */
     2390#define VERR_CR_PKIX_SIGNATURE_NEGATIVE             (-23507)
     2391/** Invalid signature length. */
     2392#define VERR_CR_PKIX_INVALID_SIGNATURE_LENGTH       (-23508)
     2393/** PKIX signature no does not match up to the current data. */
     2394#define VERR_CR_PKIX_SIGNATURE_MISMATCH             (-23509)
     2395/** PKIX cipher algorithm parameters are not implemented. */
     2396#define VERR_CR_PKIX_CIPHER_ALGO_PARAMS_NOT_IMPL    (-23510)
     2397/** ipher algorithm is not known to us. */
     2398#define VERR_CR_PKIX_CIPHER_ALGO_NOT_KNOWN          (-23511)
     2399/** PKIX cipher algorithm is not known to OpenSSL. */
     2400#define VERR_CR_PKIX_OSSL_CIPHER_ALGO_NOT_KNOWN     (-23512)
     2401/** PKIX cipher algorithm is not known to OpenSSL EVP API. */
     2402#define VERR_CR_PKIX_OSSL_CIPHER_ALGO_NOT_KNOWN_EVP (-23513)
     2403/** OpenSSL failed to init PKIX cipher algorithm context. */
     2404#define VERR_CR_PKIX_OSSL_CIPHER_ALOG_INIT_FAILED   (-23514)
     2405/** Final OpenSSL PKIX verification failed. */
     2406#define VERR_CR_PKIX_OSSL_VERIFY_FINAL_FAILED       (-23515)
     2407/** OpenSSL failed to decode the public key. */
     2408#define VERR_CR_PKIX_OSSL_D2I_PUBLIC_KEY_FAILED     (-23516)
     2409/** The EVP_PKEY_type API in OpenSSL failed.  */
     2410#define VERR_CR_PKIX_OSSL_EVP_PKEY_TYPE_ERROR       (-23517)
     2411/** @} */
     2412
     2413/** @name RTCrStore status codes.
     2414 * @{ */
     2415/** Generic store error. */
     2416#define VERR_CR_STORE_GENERIC_ERROR                 (-23700)
     2417/** @} */
     2418
     2419/** @name RTCrRsa status codes.
     2420 * @{ */
     2421/** Generic RSA error. */
     2422#define VERR_CR_RSA_GENERIC_ERROR                   (-23900)
     2423/** @} */
     2424
     2425/** @name RTBigNum status codes.
     2426 * @{ */
     2427/** Sensitive input requires the result(s) to be initialized as sensitive. */
     2428#define VERR_BIGNUM_SENSITIVE_INPUT                 (-24000)
     2429/** Attempt to divide by zero. */
     2430#define VERR_BIGNUM_DIV_BY_ZERO                     (-24001)
     2431/** Negative exponent makes no sense to integer math. */
     2432#define VERR_BIGNUM_NEGATIVE_EXPONENT               (-24002)
     2433
     2434/** @} */
     2435
     2436/** @name RTCrDigest status codes.
     2437 * @{ */
     2438/** OpenSSL failed to initialize the digest algorithm contextn. */
     2439#define VERR_CR_DIGEST_OSSL_DIGEST_INIT_ERROR       (-24201)
     2440/** OpenSSL failed to clone the digest algorithm contextn. */
     2441#define VERR_CR_DIGEST_OSSL_DIGEST_CTX_COPY_ERROR   (-24201)
     2442/** @} */
     2443
    19252444/* SED-END */
    19262445
  • trunk/include/iprt/ldr.h

    r49044 r51770  
    44
    55/*
    6  * Copyright (C) 2006-2011 Oracle Corporation
     6 * Copyright (C) 2006-2014 Oracle Corporation
    77 *
    88 * This file is part of VirtualBox Open Source Edition (OSE), as
     
    132132
    133133
     134/** Pointer to a loader reader instance. */
     135typedef struct RTLDRREADER *PRTLDRREADER;
     136/**
     137 * Loader image reader instance.
     138 *
     139 * @remarks The reader will typically have a larger structure wrapping this one
     140 *          for storing necessary instance variables.
     141 *
     142 *          The loader ASSUMES the caller serializes all access to the
     143 *          individual loader module handlers, thus no serialization is required
     144 *          when implementing this interface.
     145 */
     146typedef struct RTLDRREADER
     147{
     148    /** Magic value (RTLDRREADER_MAGIC). */
     149    uintptr_t           uMagic;
     150
     151    /**
     152     * Reads bytes at a give place in the raw image.
     153     *
     154     * @returns iprt status code.
     155     * @param   pReader     Pointer to the reader instance.
     156     * @param   pvBuf       Where to store the bits.
     157     * @param   cb          Number of bytes to read.
     158     * @param   off         Where to start reading relative to the start of the raw image.
     159     */
     160    DECLCALLBACKMEMBER(int, pfnRead)(PRTLDRREADER pReader, void *pvBuf, size_t cb, RTFOFF off);
     161
     162    /**
     163     * Tells end position of last read.
     164     *
     165     * @returns position relative to start of the raw image.
     166     * @param   pReader     Pointer to the reader instance.
     167     */
     168    DECLCALLBACKMEMBER(RTFOFF, pfnTell)(PRTLDRREADER pReader);
     169
     170    /**
     171     * Gets the size of the raw image bits.
     172     *
     173     * @returns size of raw image bits in bytes.
     174     * @param   pReader     Pointer to the reader instance.
     175     */
     176    DECLCALLBACKMEMBER(RTFOFF, pfnSize)(PRTLDRREADER pReader);
     177
     178    /**
     179     * Map the bits into memory.
     180     *
     181     * The mapping will be freed upon calling pfnDestroy() if not pfnUnmap()
     182     * is called before that. The mapping is read only.
     183     *
     184     * @returns iprt status code.
     185     * @param   pReader     Pointer to the reader instance.
     186     * @param   ppvBits     Where to store the address of the memory mapping on success.
     187     *                      The size of the mapping can be obtained by calling pfnSize().
     188     */
     189    DECLCALLBACKMEMBER(int, pfnMap)(PRTLDRREADER pReader, const void **ppvBits);
     190
     191    /**
     192     * Unmap bits.
     193     *
     194     * @returns iprt status code.
     195     * @param   pReader     Pointer to the reader instance.
     196     * @param   pvBits      Memory pointer returned by pfnMap().
     197     */
     198    DECLCALLBACKMEMBER(int, pfnUnmap)(PRTLDRREADER pReader, const void *pvBits);
     199
     200    /**
     201     * Gets the most appropriate log name.
     202     *
     203     * @returns Pointer to readonly log name.
     204     * @param   pReader     Pointer to the reader instance.
     205     */
     206    DECLCALLBACKMEMBER(const char *, pfnLogName)(PRTLDRREADER pReader);
     207
     208    /**
     209     * Releases all resources associated with the reader instance.
     210     * The instance is invalid after this call returns.
     211     *
     212     * @returns iprt status code.
     213     * @param   pReader     Pointer to the reader instance.
     214     */
     215    DECLCALLBACKMEMBER(int, pfnDestroy)(PRTLDRREADER pReader);
     216} RTLDRREADER;
     217
     218/** Magic value for RTLDRREADER (Gordon Matthew Thomas Sumner / Sting). */
     219#define RTLDRREADER_MAGIC   UINT32_C(0x19511002)
     220
     221
    134222/**
    135223 * Gets the default file suffix for DLL/SO/DYLIB/whatever.
     
    273361 * This will skip a few of the stricter validations when loading images. */
    274362#define RTLDR_O_FOR_DEBUG       RT_BIT_32(0)
     363/** Open for signature validation. */
     364#define RTLDR_O_FOR_VALIDATION  RT_BIT_32(1)
    275365/** Mask of valid flags. */
    276 #define RTLDR_O_VALID_MASK      UINT32_C(0x00000001)
     366#define RTLDR_O_VALID_MASK      UINT32_C(0x00000003)
    277367/** @} */
    278368
     
    300390RTDECL(int) RTLdrOpenkLdr(const char *pszFilename, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod);
    301391
     392/**
     393 * Open part with reader.
     394 *
     395 * @returns iprt status code.
     396 * @param   pReader     The loader reader instance which will provide the raw
     397 *                      image bits.  The reader instance will be consumed on
     398 *                      success.  On failure, the caller has to do the cleaning
     399 *                      up.
     400 * @param   fFlags      Valid RTLDR_O_XXX combination.
     401 * @param   enmArch     Architecture specifier.
     402 * @param   phMod       Where to store the handle.
     403 * @param   pErrInfo    Where to return extended error information. Optional.
     404 */
     405RTDECL(int) RTLdrOpenWithReader(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phMod, PRTERRINFO pErrInfo);
    302406
    303407/**
     
    840944     * Returns a 32-bit or 64-bit signed integer value in the buffer. */
    841945    RTLDRPROP_TIMESTAMP_SECONDS,
     946    /** Checks if the image is signed.
     947     * Returns a bool.  */
     948    RTLDRPROP_IS_SIGNED,
     949    /** Retrives the PKCS \#7 SignedData blob that signs the image.
     950     * Returns variable sized buffer containing the ASN.1 BER encoding.
     951     *
     952     * @remarks This generally starts with a PKCS \#7 Content structure, the
     953     *          SignedData bit is found a few levels down into this as per RFC. */
     954    RTLDRPROP_PKCS7_SIGNED_DATA,
     955
     956    /** Query whether code signature checks are enabled.  */
     957    RTLDRPROP_SIGNATURE_CHECKS_ENFORCED,
     958
    842959    /** End of valid properties.  */
    843960    RTLDRPROP_END,
     
    856973 * @retval  VERR_INVALID_FUNCTION if the function value is wrong.
    857974 * @retval  VERR_INVALID_PARAMETER if the buffer size is wrong.
     975 * @retval  VERR_BUFFER_OVERFLOW if the function doesn't have a fixed size
     976 *          buffer and the buffer isn't big enough.  Use RTLdrQueryPropEx.
    858977 * @retval  VERR_INVALID_HANDLE if the handle is invalid.
    859978 *
     
    865984RTDECL(int) RTLdrQueryProp(RTLDRMOD hLdrMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf);
    866985
     986/**
     987 * Generic method for querying image properties, extended version.
     988 *
     989 * @returns IPRT status code.
     990 * @retval  VERR_NOT_SUPPORTED if the property query isn't supported (either all
     991 *          or that specific property).  The caller must handle this result.
     992 * @retval  VERR_NOT_FOUND the property was not found in the module.  The caller
     993 *          must also normally deal with this.
     994 * @retval  VERR_INVALID_FUNCTION if the function value is wrong.
     995 * @retval  VERR_INVALID_PARAMETER if the fixed buffer size is wrong. Correct
     996 *          size in @a *pcbRet.
     997 * @retval  VERR_BUFFER_OVERFLOW if the function doesn't have a fixed size
     998 *          buffer and the buffer isn't big enough. Correct size in @a *pcbRet.
     999 * @retval  VERR_INVALID_HANDLE if the handle is invalid.
     1000 *
     1001 * @param   hLdrMod         The module handle.
     1002 * @param   enmLdrProp      The property to query.
     1003 * @param   pvBuf           Pointer to the return buffer.
     1004 * @param   cbBuf           The size of the return buffer.
     1005 * @param   pcbRet          Where to return the amount of data returned.  On
     1006 *                          buffer size errors, this is set to the correct size.
     1007 *                          Optional.
     1008 */
     1009RTDECL(int) RTLdrQueryPropEx(RTLDRMOD hLdrMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf, size_t *pcbBuf);
     1010
     1011
     1012/**
     1013 * Signature type, see FNRTLDRVALIDATESIGNEDDATA.
     1014 */
     1015typedef enum RTLDRSIGNATURETYPE
     1016{
     1017    /** Invalid value. */
     1018    RTLDRSIGNATURETYPE_INVALID = 0,
     1019    /** A RTPKCS7CONTENTINFO structure w/ RTPKCS7SIGNEDDATA inside.
     1020     * It's parsed, so the whole binary ASN.1 representation can be found by
     1021     * using RTASN1CORE_GET_RAW_ASN1_PTR() and RTASN1CORE_GET_RAW_ASN1_SIZE(). */
     1022    RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA,
     1023    /** End of valid values. */
     1024    RTLDRSIGNATURETYPE_END,
     1025    /** Make sure the size is 32-bit. */
     1026    RTLDRSIGNATURETYPE_32BIT_HACK = 0x7fffffff
     1027} RTLDRSIGNATURETYPE;
     1028
     1029/**
     1030 * Callback used by RTLdrVerifySignature to verify the signature and associated
     1031 * certificates.
     1032 *
     1033 * @returns IPRT status code.
     1034 * @param   hLdrMod         The module handle.
     1035 * @param   enmSignature    The signature format.
     1036 * @param   pvSignature     The signature data. Format given by @a enmSignature.
     1037 * @param   cbSignature     The size of the buffer @a pvSignature points to.
     1038 * @param   pErrInfo        Pointer to an error info buffer, optional.
     1039 * @param   pvUser          User argument.
     1040 *
     1041 */
     1042typedef DECLCALLBACK(int) FNRTLDRVALIDATESIGNEDDATA(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature, void const *pvSignature, size_t cbSignature,
     1043                                                    PRTERRINFO pErrInfo, void *pvUser);
     1044/** Pointer to a signature verification callback. */
     1045typedef FNRTLDRVALIDATESIGNEDDATA *PFNRTLDRVALIDATESIGNEDDATA;
     1046
     1047/**
     1048 * Verify the image signature.
     1049 *
     1050 * This may permform additional integrity checks on the image structures that
     1051 * was not done when opening the image.
     1052 *
     1053 * @returns IPRT status code.
     1054 * @retval  VERR_LDRVI_NOT_SIGNED if not signed.
     1055 *
     1056 * @param   hLdrMod         The module handle.
     1057 * @param   pfnCallback     Callback that does the signature and certificate
     1058 *                          verficiation.
     1059 * @param   pvUser          User argument for the callback.
     1060 * @param   pErrInfo        Pointer to an error info buffer. Optional.
     1061 */
     1062RTDECL(int) RTLdrVerifySignature(RTLDRMOD hLdrMod, PFNRTLDRVALIDATESIGNEDDATA pfnCallback, void *pvUser, PRTERRINFO pErrInfo);
     1063
     1064/**
     1065 * Calculate the image hash according the image signing rules.
     1066 *
     1067 * @returns IPRT status code.
     1068 * @param   hLdrMod         The module handle.
     1069 * @param   enmDigest       Which kind of digest.
     1070 * @param   pszDigest       Where to store the image digest.
     1071 * @param   cbDigest        Size of the buffer @a pszDigest points at.
     1072 */
     1073RTDECL(int) RTLdrHashImage(RTLDRMOD hLdrMod, RTDIGESTTYPE enmDigest, char *pszDigest, size_t cbDigest);
     1074
    8671075RT_C_DECLS_END
    8681076
  • trunk/include/iprt/log.h

    r46392 r51770  
    18171817RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list args);
    18181818
     1819/**
     1820 * Dumper vprintf-like function outputting to a logger.
     1821 *
     1822 * @param   pvUser          Pointer to the logger instance to use, NULL for
     1823 *                          default instance.
     1824 * @param   pszFormat       Format string.
     1825 * @param   va              Format arguments.
     1826 */
     1827RTDECL(void) RTLogDumpPrintfV(void *pvUser, const char *pszFormat, va_list va);
     1828
    18191829
    18201830#ifndef DECLARED_FNRTSTROUTPUT          /* duplicated in iprt/string.h */
  • trunk/include/iprt/mangling.h

    r51767 r51770  
    274274# define RTAvlULRemoveBestFit                           RT_MANGLER(RTAvlULRemoveBestFit)
    275275# define RTBase64Decode                                 RT_MANGLER(RTBase64Decode)
     276# define RTBase64DecodeEx                               RT_MANGLER(RTBase64DecodeEx)
    276277# define RTBase64DecodedSize                            RT_MANGLER(RTBase64DecodedSize)
     278# define RTBase64DecodedSizeEx                          RT_MANGLER(RTBase64DecodedSizeEx)
    277279# define RTBase64Encode                                 RT_MANGLER(RTBase64Encode)
    278280# define RTBase64EncodedLength                          RT_MANGLER(RTBase64EncodedLength)
     
    801803# define RTLogPrintf                                    RT_MANGLER(RTLogPrintf)
    802804# define RTLogPrintfV                                   RT_MANGLER(RTLogPrintfV)
     805# define RTLogDumpPrintfV                               RT_MANGLER(RTLogDumpPrintfV)
    803806# define RTLogRelDefaultInstance                        RT_MANGLER(RTLogRelDefaultInstance)
    804807# define RTLogRelLogger                                 RT_MANGLER(RTLogRelLogger)
     
    10961099# define RTProcGetPriority                              RT_MANGLER(RTProcGetPriority)
    10971100# define RTProcIsRunningByName                          RT_MANGLER(RTProcIsRunningByName)
     1101# define RTProcQueryParent                              RT_MANGLER(RTProcQueryParent)
    10981102# define RTProcQueryUsername                            RT_MANGLER(RTProcQueryUsername)
    10991103# define RTProcQueryUsernameA                           RT_MANGLER(RTProcQueryUsernameA)
     
    14391443# define RTStrmPrintf                                   RT_MANGLER(RTStrmPrintf)
    14401444# define RTStrmPrintfV                                  RT_MANGLER(RTStrmPrintfV)
     1445# define RTStrmDumpPrintfV                              RT_MANGLER(RTStrmDumpPrintfV)
    14411446# define RTStrmPutCh                                    RT_MANGLER(RTStrmPutCh)
    14421447# define RTStrmPutStr                                   RT_MANGLER(RTStrmPutStr)
     
    17651770# define RTUtf16CalcUtf8LenEx                           RT_MANGLER(RTUtf16CalcUtf8LenEx)
    17661771# define RTUtf16Cmp                                     RT_MANGLER(RTUtf16Cmp)
     1772# define RTUtf16CmpAscii                                RT_MANGLER(RTUtf16CmpAscii)
    17671773# define RTUtf16DupExTag                                RT_MANGLER(RTUtf16DupExTag)
    17681774# define RTUtf16DupTag                                  RT_MANGLER(RTUtf16DupTag)
     
    19081914# define RTZipTarFsStreamFromIoStream                   RT_MANGLER(RTZipTarFsStreamFromIoStream)
    19091915# define RTZipXarFsStreamFromIoStream                   RT_MANGLER(RTZipXarFsStreamFromIoStream)
     1916
     1917/* sort/merge into the above later: */
     1918# define RTAsn1ContentAllocZ                            RT_MANGLER(RTAsn1ContentAllocZ)
     1919# define RTAsn1ContentDup                               RT_MANGLER(RTAsn1ContentDup)
     1920# define RTAsn1ContentFree                              RT_MANGLER(RTAsn1ContentFree)
     1921# define RTAsn1ContentReallocZ                          RT_MANGLER(RTAsn1ContentReallocZ)
     1922# define RTAsn1ContextTagN_Clone                        RT_MANGLER(RTAsn1ContextTagN_Clone)
     1923# define RTAsn1ContextTagN_Init                         RT_MANGLER(RTAsn1ContextTagN_Init)
     1924# define RTAsn1Dummy_InitEx                             RT_MANGLER(RTAsn1Dummy_InitEx)
     1925# define RTAsn1MemAllocZ                                RT_MANGLER(RTAsn1MemAllocZ)
     1926# define RTAsn1MemDup                                   RT_MANGLER(RTAsn1MemDup)
     1927# define RTAsn1MemFree                                  RT_MANGLER(RTAsn1MemFree)
     1928# define RTAsn1MemGrowArray                             RT_MANGLER(RTAsn1MemGrowArray)
     1929# define RTAsn1MemInitAllocation                        RT_MANGLER(RTAsn1MemInitAllocation)
     1930# define RTAsn1SeqOfCore_Clone                          RT_MANGLER(RTAsn1SeqOfCore_Clone)
     1931# define RTAsn1SeqOfCore_Init                           RT_MANGLER(RTAsn1SeqOfCore_Init)
     1932# define RTAsn1SequenceCore_Clone                       RT_MANGLER(RTAsn1SequenceCore_Clone)
     1933# define RTAsn1SequenceCore_Init                        RT_MANGLER(RTAsn1SequenceCore_Init)
     1934# define RTAsn1SetCore_Clone                            RT_MANGLER(RTAsn1SetCore_Clone)
     1935# define RTAsn1SetCore_Init                             RT_MANGLER(RTAsn1SetCore_Init)
     1936# define RTAsn1SetOfCore_Clone                          RT_MANGLER(RTAsn1SetOfCore_Clone)
     1937# define RTAsn1SetOfCore_Init                           RT_MANGLER(RTAsn1SetOfCore_Init)
     1938# define RTAsn1VtCheckSanity                            RT_MANGLER(RTAsn1VtCheckSanity)
     1939# define RTAsn1VtClone                                  RT_MANGLER(RTAsn1VtClone)
     1940# define RTAsn1VtCompare                                RT_MANGLER(RTAsn1VtCompare)
     1941# define RTAsn1VtDeepEnum                               RT_MANGLER(RTAsn1VtDeepEnum)
     1942# define RTAsn1VtDelete                                 RT_MANGLER(RTAsn1VtDelete)
     1943# define RTAsn1CursorCheckEnd                           RT_MANGLER(RTAsn1CursorCheckEnd)
     1944# define RTAsn1CursorGetBitString                       RT_MANGLER(RTAsn1CursorGetBitString)
     1945# define RTAsn1CursorGetBitStringEx                     RT_MANGLER(RTAsn1CursorGetBitStringEx)
     1946# define RTAsn1CursorGetBmpString                       RT_MANGLER(RTAsn1CursorGetBmpString)
     1947# define RTAsn1CursorGetBoolean                         RT_MANGLER(RTAsn1CursorGetBoolean)
     1948# define RTAsn1CursorGetContextTagNCursor               RT_MANGLER(RTAsn1CursorGetContextTagNCursor)
     1949# define RTAsn1CursorGetCore                            RT_MANGLER(RTAsn1CursorGetCore)
     1950# define RTAsn1CursorGetDynType                         RT_MANGLER(RTAsn1CursorGetDynType)
     1951# define RTAsn1CursorGetIa5String                       RT_MANGLER(RTAsn1CursorGetIa5String)
     1952# define RTAsn1CursorGetInteger                         RT_MANGLER(RTAsn1CursorGetInteger)
     1953# define RTAsn1CursorGetNull                            RT_MANGLER(RTAsn1CursorGetNull)
     1954# define RTAsn1CursorGetObjId                           RT_MANGLER(RTAsn1CursorGetObjId)
     1955# define RTAsn1CursorGetOctetString                     RT_MANGLER(RTAsn1CursorGetOctetString)
     1956# define RTAsn1CursorGetSequenceCursor                  RT_MANGLER(RTAsn1CursorGetSequenceCursor)
     1957# define RTAsn1CursorGetSetCursor                       RT_MANGLER(RTAsn1CursorGetSetCursor)
     1958# define RTAsn1CursorGetString                          RT_MANGLER(RTAsn1CursorGetString)
     1959# define RTAsn1CursorGetTime                            RT_MANGLER(RTAsn1CursorGetTime)
     1960# define RTAsn1CursorGetUtf8String                      RT_MANGLER(RTAsn1CursorGetUtf8String)
     1961# define RTAsn1CursorInitAllocation                     RT_MANGLER(RTAsn1CursorInitAllocation)
     1962# define RTAsn1CursorInitPrimary                        RT_MANGLER(RTAsn1CursorInitPrimary)
     1963# define RTAsn1CursorInitSubFromCore                    RT_MANGLER(RTAsn1CursorInitSubFromCore)
     1964# define RTAsn1CursorIsNextEx                           RT_MANGLER(RTAsn1CursorIsNextEx)
     1965# define RTAsn1CursorMatchTagClassFlagsEx               RT_MANGLER(RTAsn1CursorMatchTagClassFlagsEx)
     1966# define RTAsn1CursorPeek                               RT_MANGLER(RTAsn1CursorPeek)
     1967# define RTAsn1CursorReadHdr                            RT_MANGLER(RTAsn1CursorReadHdr)
     1968# define RTAsn1CursorSetInfo                            RT_MANGLER(RTAsn1CursorSetInfo)
     1969# define RTAsn1CursorSetInfoV                           RT_MANGLER(RTAsn1CursorSetInfoV)
     1970# define RTAsn1Dump                                     RT_MANGLER(RTAsn1Dump)
     1971# define RTAsn1EncodePrepare                            RT_MANGLER(RTAsn1EncodePrepare)
     1972# define RTAsn1EncodeRecalcHdrSize                      RT_MANGLER(RTAsn1EncodeRecalcHdrSize)
     1973# define RTAsn1EncodeWrite                              RT_MANGLER(RTAsn1EncodeWrite)
     1974# define RTAsnEncodeWriteHeader                         RT_MANGLER(RTAsnEncodeWriteHeader)
     1975# define RTAsn1BitString_CheckSanity                    RT_MANGLER(RTAsn1BitString_CheckSanity)
     1976# define RTAsn1BitString_Clone                          RT_MANGLER(RTAsn1BitString_Clone)
     1977# define RTAsn1BitString_Compare                        RT_MANGLER(RTAsn1BitString_Compare)
     1978# define RTAsn1BitString_Delete                         RT_MANGLER(RTAsn1BitString_Delete)
     1979# define RTAsn1BitString_Enum                           RT_MANGLER(RTAsn1BitString_Enum)
     1980# define RTAsn1BitString_GetAsUInt64                    RT_MANGLER(RTAsn1BitString_GetAsUInt64)
     1981# define RTAsn1BitString_Init                           RT_MANGLER(RTAsn1BitString_Init)
     1982# define RTAsn1SeqOfBitStrings_CheckSanity              RT_MANGLER(RTAsn1SeqOfBitStrings_CheckSanity)
     1983# define RTAsn1SeqOfBitStrings_Clone                    RT_MANGLER(RTAsn1SeqOfBitStrings_Clone)
     1984# define RTAsn1SeqOfBitStrings_Compare                  RT_MANGLER(RTAsn1SeqOfBitStrings_Compare)
     1985# define RTAsn1SeqOfBitStrings_Delete                   RT_MANGLER(RTAsn1SeqOfBitStrings_Delete)
     1986# define RTAsn1SeqOfBitStrings_Enum                     RT_MANGLER(RTAsn1SeqOfBitStrings_Enum)
     1987# define RTAsn1SeqOfBitStrings_Init                     RT_MANGLER(RTAsn1SeqOfBitStrings_Init)
     1988# define RTAsn1SetOfBitStrings_CheckSanity              RT_MANGLER(RTAsn1SetOfBitStrings_CheckSanity)
     1989# define RTAsn1SetOfBitStrings_Clone                    RT_MANGLER(RTAsn1SetOfBitStrings_Clone)
     1990# define RTAsn1SetOfBitStrings_Compare                  RT_MANGLER(RTAsn1SetOfBitStrings_Compare)
     1991# define RTAsn1SetOfBitStrings_Delete                   RT_MANGLER(RTAsn1SetOfBitStrings_Delete)
     1992# define RTAsn1SetOfBitStrings_Enum                     RT_MANGLER(RTAsn1SetOfBitStrings_Enum)
     1993# define RTAsn1SetOfBitStrings_Init                     RT_MANGLER(RTAsn1SetOfBitStrings_Init)
     1994# define RTAsn1BitString_DecodeAsn1                     RT_MANGLER(RTAsn1BitString_DecodeAsn1)
     1995# define RTAsn1BitString_DecodeAsn1Ex                   RT_MANGLER(RTAsn1BitString_DecodeAsn1Ex)
     1996# define RTAsn1SeqOfBitStrings_DecodeAsn1               RT_MANGLER(RTAsn1SeqOfBitStrings_DecodeAsn1)
     1997# define RTAsn1SetOfBitStrings_DecodeAsn1               RT_MANGLER(RTAsn1SetOfBitStrings_DecodeAsn1)
     1998# define RTAsn1Boolean_CheckSanity                      RT_MANGLER(RTAsn1Boolean_CheckSanity)
     1999# define RTAsn1Boolean_Clone                            RT_MANGLER(RTAsn1Boolean_Clone)
     2000# define RTAsn1Boolean_Compare                          RT_MANGLER(RTAsn1Boolean_Compare)
     2001# define RTAsn1Boolean_Delete                           RT_MANGLER(RTAsn1Boolean_Delete)
     2002# define RTAsn1Boolean_Enum                             RT_MANGLER(RTAsn1Boolean_Enum)
     2003# define RTAsn1Boolean_Init                             RT_MANGLER(RTAsn1Boolean_Init)
     2004# define RTAsn1Boolean_InitDefault                      RT_MANGLER(RTAsn1Boolean_InitDefault)
     2005# define RTAsn1Boolean_Set                              RT_MANGLER(RTAsn1Boolean_Set)
     2006# define RTAsn1SeqOfBooleans_CheckSanity                RT_MANGLER(RTAsn1SeqOfBooleans_CheckSanity)
     2007# define RTAsn1SeqOfBooleans_Clone                      RT_MANGLER(RTAsn1SeqOfBooleans_Clone)
     2008# define RTAsn1SeqOfBooleans_Compare                    RT_MANGLER(RTAsn1SeqOfBooleans_Compare)
     2009# define RTAsn1SeqOfBooleans_Delete                     RT_MANGLER(RTAsn1SeqOfBooleans_Delete)
     2010# define RTAsn1SeqOfBooleans_Enum                       RT_MANGLER(RTAsn1SeqOfBooleans_Enum)
     2011# define RTAsn1SeqOfBooleans_Init                       RT_MANGLER(RTAsn1SeqOfBooleans_Init)
     2012# define RTAsn1SetOfBooleans_CheckSanity                RT_MANGLER(RTAsn1SetOfBooleans_CheckSanity)
     2013# define RTAsn1SetOfBooleans_Clone                      RT_MANGLER(RTAsn1SetOfBooleans_Clone)
     2014# define RTAsn1SetOfBooleans_Compare                    RT_MANGLER(RTAsn1SetOfBooleans_Compare)
     2015# define RTAsn1SetOfBooleans_Delete                     RT_MANGLER(RTAsn1SetOfBooleans_Delete)
     2016# define RTAsn1SetOfBooleans_Enum                       RT_MANGLER(RTAsn1SetOfBooleans_Enum)
     2017# define RTAsn1SetOfBooleans_Init                       RT_MANGLER(RTAsn1SetOfBooleans_Init)
     2018# define RTAsn1Boolean_DecodeAsn1                       RT_MANGLER(RTAsn1Boolean_DecodeAsn1)
     2019# define RTAsn1SeqOfBooleans_DecodeAsn1                 RT_MANGLER(RTAsn1SeqOfBooleans_DecodeAsn1)
     2020# define RTAsn1SetOfBooleans_DecodeAsn1                 RT_MANGLER(RTAsn1SetOfBooleans_DecodeAsn1)
     2021# define RTAsn1Core_ChangeTag                           RT_MANGLER(RTAsn1Core_ChangeTag)
     2022# define RTAsn1Core_CheckSanity                         RT_MANGLER(RTAsn1Core_CheckSanity)
     2023# define RTAsn1Core_Clone                               RT_MANGLER(RTAsn1Core_Clone)
     2024# define RTAsn1Core_CloneContent                        RT_MANGLER(RTAsn1Core_CloneContent)
     2025# define RTAsn1Core_CloneNoContent                      RT_MANGLER(RTAsn1Core_CloneNoContent)
     2026# define RTAsn1Core_Compare                             RT_MANGLER(RTAsn1Core_Compare)
     2027# define RTAsn1Core_CompareEx                           RT_MANGLER(RTAsn1Core_CompareEx)
     2028# define RTAsn1Core_Delete                              RT_MANGLER(RTAsn1Core_Delete)
     2029# define RTAsn1Core_Enum                                RT_MANGLER(RTAsn1Core_Enum)
     2030# define RTAsn1Core_Init                                RT_MANGLER(RTAsn1Core_Init)
     2031# define RTAsn1Core_InitDefault                         RT_MANGLER(RTAsn1Core_InitDefault)
     2032# define RTAsn1Core_InitEx                              RT_MANGLER(RTAsn1Core_InitEx)
     2033# define RTAsn1Core_ResetImplict                        RT_MANGLER(RTAsn1Core_ResetImplict)
     2034# define RTAsn1Core_SetTagAndFlags                      RT_MANGLER(RTAsn1Core_SetTagAndFlags)
     2035# define RTAsn1SeqOfCores_CheckSanity                   RT_MANGLER(RTAsn1SeqOfCores_CheckSanity)
     2036# define RTAsn1SeqOfCores_Clone                         RT_MANGLER(RTAsn1SeqOfCores_Clone)
     2037# define RTAsn1SeqOfCores_Compare                       RT_MANGLER(RTAsn1SeqOfCores_Compare)
     2038# define RTAsn1SeqOfCores_Delete                        RT_MANGLER(RTAsn1SeqOfCores_Delete)
     2039# define RTAsn1SeqOfCores_Enum                          RT_MANGLER(RTAsn1SeqOfCores_Enum)
     2040# define RTAsn1SeqOfCores_Init                          RT_MANGLER(RTAsn1SeqOfCores_Init)
     2041# define RTAsn1SetOfCores_CheckSanity                   RT_MANGLER(RTAsn1SetOfCores_CheckSanity)
     2042# define RTAsn1SetOfCores_Clone                         RT_MANGLER(RTAsn1SetOfCores_Clone)
     2043# define RTAsn1SetOfCores_Compare                       RT_MANGLER(RTAsn1SetOfCores_Compare)
     2044# define RTAsn1SetOfCores_Delete                        RT_MANGLER(RTAsn1SetOfCores_Delete)
     2045# define RTAsn1SetOfCores_Enum                          RT_MANGLER(RTAsn1SetOfCores_Enum)
     2046# define RTAsn1SetOfCores_Init                          RT_MANGLER(RTAsn1SetOfCores_Init)
     2047# define RTAsn1Core_DecodeAsn1                          RT_MANGLER(RTAsn1Core_DecodeAsn1)
     2048# define RTAsn1SeqOfCores_DecodeAsn1                    RT_MANGLER(RTAsn1SeqOfCores_DecodeAsn1)
     2049# define RTAsn1SetOfCores_DecodeAsn1                    RT_MANGLER(RTAsn1SetOfCores_DecodeAsn1)
     2050# define RTAsn1DynType_CheckSanity                      RT_MANGLER(RTAsn1DynType_CheckSanity)
     2051# define RTAsn1DynType_Clone                            RT_MANGLER(RTAsn1DynType_Clone)
     2052# define RTAsn1DynType_Compare                          RT_MANGLER(RTAsn1DynType_Compare)
     2053# define RTAsn1DynType_Delete                           RT_MANGLER(RTAsn1DynType_Delete)
     2054# define RTAsn1DynType_Enum                             RT_MANGLER(RTAsn1DynType_Enum)
     2055# define RTAsn1DynType_Init                             RT_MANGLER(RTAsn1DynType_Init)
     2056# define RTAsn1DynType_DecodeAsn1                       RT_MANGLER(RTAsn1DynType_DecodeAsn1)
     2057# define RTAsn1Integer_CheckSanity                      RT_MANGLER(RTAsn1Integer_CheckSanity)
     2058# define RTAsn1Integer_Clone                            RT_MANGLER(RTAsn1Integer_Clone)
     2059# define RTAsn1Integer_Compare                          RT_MANGLER(RTAsn1Integer_Compare)
     2060# define RTAsn1Integer_Delete                           RT_MANGLER(RTAsn1Integer_Delete)
     2061# define RTAsn1Integer_Enum                             RT_MANGLER(RTAsn1Integer_Enum)
     2062# define RTAsn1Integer_FromBigNum                       RT_MANGLER(RTAsn1Integer_FromBigNum)
     2063# define RTAsn1Integer_Init                             RT_MANGLER(RTAsn1Integer_Init)
     2064# define RTAsn1Integer_InitDefault                      RT_MANGLER(RTAsn1Integer_InitDefault)
     2065# define RTAsn1Integer_InitU64                          RT_MANGLER(RTAsn1Integer_InitU64)
     2066# define RTAsn1Integer_ToBigNum                         RT_MANGLER(RTAsn1Integer_ToBigNum)
     2067# define RTAsn1Integer_UnsignedCompare                  RT_MANGLER(RTAsn1Integer_UnsignedCompare)
     2068# define RTAsn1Integer_UnsignedCompareWithU32           RT_MANGLER(RTAsn1Integer_UnsignedCompareWithU32)
     2069# define RTAsn1Integer_UnsignedCompareWithU64           RT_MANGLER(RTAsn1Integer_UnsignedCompareWithU64)
     2070# define RTAsn1Integer_UnsignedLastBit                  RT_MANGLER(RTAsn1Integer_UnsignedLastBit)
     2071# define RTAsn1SeqOfIntegers_CheckSanity                RT_MANGLER(RTAsn1SeqOfIntegers_CheckSanity)
     2072# define RTAsn1SeqOfIntegers_Clone                      RT_MANGLER(RTAsn1SeqOfIntegers_Clone)
     2073# define RTAsn1SeqOfIntegers_Compare                    RT_MANGLER(RTAsn1SeqOfIntegers_Compare)
     2074# define RTAsn1SeqOfIntegers_Delete                     RT_MANGLER(RTAsn1SeqOfIntegers_Delete)
     2075# define RTAsn1SeqOfIntegers_Enum                       RT_MANGLER(RTAsn1SeqOfIntegers_Enum)
     2076# define RTAsn1SeqOfIntegers_Init                       RT_MANGLER(RTAsn1SeqOfIntegers_Init)
     2077# define RTAsn1SetOfIntegers_CheckSanity                RT_MANGLER(RTAsn1SetOfIntegers_CheckSanity)
     2078# define RTAsn1SetOfIntegers_Clone                      RT_MANGLER(RTAsn1SetOfIntegers_Clone)
     2079# define RTAsn1SetOfIntegers_Compare                    RT_MANGLER(RTAsn1SetOfIntegers_Compare)
     2080# define RTAsn1SetOfIntegers_Delete                     RT_MANGLER(RTAsn1SetOfIntegers_Delete)
     2081# define RTAsn1SetOfIntegers_Enum                       RT_MANGLER(RTAsn1SetOfIntegers_Enum)
     2082# define RTAsn1SetOfIntegers_Init                       RT_MANGLER(RTAsn1SetOfIntegers_Init)
     2083# define RTAsn1Integer_DecodeAsn1                       RT_MANGLER(RTAsn1Integer_DecodeAsn1)
     2084# define RTAsn1SeqOfIntegers_DecodeAsn1                 RT_MANGLER(RTAsn1SeqOfIntegers_DecodeAsn1)
     2085# define RTAsn1SetOfIntegers_DecodeAsn1                 RT_MANGLER(RTAsn1SetOfIntegers_DecodeAsn1)
     2086# define RTAsn1Null_CheckSanity                         RT_MANGLER(RTAsn1Null_CheckSanity)
     2087# define RTAsn1Null_Clone                               RT_MANGLER(RTAsn1Null_Clone)
     2088# define RTAsn1Null_Compare                             RT_MANGLER(RTAsn1Null_Compare)
     2089# define RTAsn1Null_Delete                              RT_MANGLER(RTAsn1Null_Delete)
     2090# define RTAsn1Null_Enum                                RT_MANGLER(RTAsn1Null_Enum)
     2091# define RTAsn1Null_Init                                RT_MANGLER(RTAsn1Null_Init)
     2092# define RTAsn1Null_DecodeAsn1                          RT_MANGLER(RTAsn1Null_DecodeAsn1)
     2093# define RTAsn1ObjIdCountComponents                     RT_MANGLER(RTAsn1ObjIdCountComponents)
     2094# define RTAsn1ObjIdGetComponentsAsUInt32               RT_MANGLER(RTAsn1ObjIdGetComponentsAsUInt32)
     2095# define RTAsn1ObjIdGetLastComponentsAsUInt32           RT_MANGLER(RTAsn1ObjIdGetLastComponentsAsUInt32)
     2096# define RTAsn1ObjId_CheckSanity                        RT_MANGLER(RTAsn1ObjId_CheckSanity)
     2097# define RTAsn1ObjId_Clone                              RT_MANGLER(RTAsn1ObjId_Clone)
     2098# define RTAsn1ObjId_Compare                            RT_MANGLER(RTAsn1ObjId_Compare)
     2099# define RTAsn1ObjId_CompareWithString                  RT_MANGLER(RTAsn1ObjId_CompareWithString)
     2100# define RTAsn1ObjId_Delete                             RT_MANGLER(RTAsn1ObjId_Delete)
     2101# define RTAsn1ObjId_Enum                               RT_MANGLER(RTAsn1ObjId_Enum)
     2102# define RTAsn1ObjId_Init                               RT_MANGLER(RTAsn1ObjId_Init)
     2103# define RTAsn1ObjId_InitFromString                     RT_MANGLER(RTAsn1ObjId_InitFromString)
     2104# define RTAsn1ObjId_StartsWith                         RT_MANGLER(RTAsn1ObjId_StartsWith)
     2105# define RTAsn1SeqOfObjIds_CheckSanity                  RT_MANGLER(RTAsn1SeqOfObjIds_CheckSanity)
     2106# define RTAsn1SeqOfObjIds_Clone                        RT_MANGLER(RTAsn1SeqOfObjIds_Clone)
     2107# define RTAsn1SeqOfObjIds_Compare                      RT_MANGLER(RTAsn1SeqOfObjIds_Compare)
     2108# define RTAsn1SeqOfObjIds_Delete                       RT_MANGLER(RTAsn1SeqOfObjIds_Delete)
     2109# define RTAsn1SeqOfObjIds_Enum                         RT_MANGLER(RTAsn1SeqOfObjIds_Enum)
     2110# define RTAsn1SeqOfObjIds_Init                         RT_MANGLER(RTAsn1SeqOfObjIds_Init)
     2111# define RTAsn1SetOfObjIds_CheckSanity                  RT_MANGLER(RTAsn1SetOfObjIds_CheckSanity)
     2112# define RTAsn1SetOfObjIds_Clone                        RT_MANGLER(RTAsn1SetOfObjIds_Clone)
     2113# define RTAsn1SetOfObjIds_Compare                      RT_MANGLER(RTAsn1SetOfObjIds_Compare)
     2114# define RTAsn1SetOfObjIds_Delete                       RT_MANGLER(RTAsn1SetOfObjIds_Delete)
     2115# define RTAsn1SetOfObjIds_Enum                         RT_MANGLER(RTAsn1SetOfObjIds_Enum)
     2116# define RTAsn1SetOfObjIds_Init                         RT_MANGLER(RTAsn1SetOfObjIds_Init)
     2117# define RTAsn1ObjId_DecodeAsn1                         RT_MANGLER(RTAsn1ObjId_DecodeAsn1)
     2118# define RTAsn1SeqOfObjIds_DecodeAsn1                   RT_MANGLER(RTAsn1SeqOfObjIds_DecodeAsn1)
     2119# define RTAsn1SetOfObjIds_DecodeAsn1                   RT_MANGLER(RTAsn1SetOfObjIds_DecodeAsn1)
     2120# define RTAsn1OctetString_CheckSanity                  RT_MANGLER(RTAsn1OctetString_CheckSanity)
     2121# define RTAsn1OctetString_Clone                        RT_MANGLER(RTAsn1OctetString_Clone)
     2122# define RTAsn1OctetString_Compare                      RT_MANGLER(RTAsn1OctetString_Compare)
     2123# define RTAsn1OctetString_Delete                       RT_MANGLER(RTAsn1OctetString_Delete)
     2124# define RTAsn1OctetString_Enum                         RT_MANGLER(RTAsn1OctetString_Enum)
     2125# define RTAsn1OctetString_Init                         RT_MANGLER(RTAsn1OctetString_Init)
     2126# define RTAsn1SeqOfOctetStrings_CheckSanity            RT_MANGLER(RTAsn1SeqOfOctetStrings_CheckSanity)
     2127# define RTAsn1SeqOfOctetStrings_Clone                  RT_MANGLER(RTAsn1SeqOfOctetStrings_Clone)
     2128# define RTAsn1SeqOfOctetStrings_Compare                RT_MANGLER(RTAsn1SeqOfOctetStrings_Compare)
     2129# define RTAsn1SeqOfOctetStrings_Delete                 RT_MANGLER(RTAsn1SeqOfOctetStrings_Delete)
     2130# define RTAsn1SeqOfOctetStrings_Enum                   RT_MANGLER(RTAsn1SeqOfOctetStrings_Enum)
     2131# define RTAsn1SeqOfOctetStrings_Init                   RT_MANGLER(RTAsn1SeqOfOctetStrings_Init)
     2132# define RTAsn1SetOfOctetStrings_CheckSanity            RT_MANGLER(RTAsn1SetOfOctetStrings_CheckSanity)
     2133# define RTAsn1SetOfOctetStrings_Clone                  RT_MANGLER(RTAsn1SetOfOctetStrings_Clone)
     2134# define RTAsn1SetOfOctetStrings_Compare                RT_MANGLER(RTAsn1SetOfOctetStrings_Compare)
     2135# define RTAsn1SetOfOctetStrings_Delete                 RT_MANGLER(RTAsn1SetOfOctetStrings_Delete)
     2136# define RTAsn1SetOfOctetStrings_Enum                   RT_MANGLER(RTAsn1SetOfOctetStrings_Enum)
     2137# define RTAsn1SetOfOctetStrings_Init                   RT_MANGLER(RTAsn1SetOfOctetStrings_Init)
     2138# define RTAsn1OctetString_DecodeAsn1                   RT_MANGLER(RTAsn1OctetString_DecodeAsn1)
     2139# define RTAsn1SeqOfOctetStrings_DecodeAsn1             RT_MANGLER(RTAsn1SeqOfOctetStrings_DecodeAsn1)
     2140# define RTAsn1SetOfOctetStrings_DecodeAsn1             RT_MANGLER(RTAsn1SetOfOctetStrings_DecodeAsn1)
     2141# define RTAsn1BmpString_CheckSanity                    RT_MANGLER(RTAsn1BmpString_CheckSanity)
     2142# define RTAsn1BmpString_Clone                          RT_MANGLER(RTAsn1BmpString_Clone)
     2143# define RTAsn1BmpString_Compare                        RT_MANGLER(RTAsn1BmpString_Compare)
     2144# define RTAsn1BmpString_Delete                         RT_MANGLER(RTAsn1BmpString_Delete)
     2145# define RTAsn1BmpString_Enum                           RT_MANGLER(RTAsn1BmpString_Enum)
     2146# define RTAsn1BmpString_Init                           RT_MANGLER(RTAsn1BmpString_Init)
     2147# define RTAsn1GeneralString_CheckSanity                RT_MANGLER(RTAsn1GeneralString_CheckSanity)
     2148# define RTAsn1GeneralString_Clone                      RT_MANGLER(RTAsn1GeneralString_Clone)
     2149# define RTAsn1GeneralString_Compare                    RT_MANGLER(RTAsn1GeneralString_Compare)
     2150# define RTAsn1GeneralString_Delete                     RT_MANGLER(RTAsn1GeneralString_Delete)
     2151# define RTAsn1GeneralString_Enum                       RT_MANGLER(RTAsn1GeneralString_Enum)
     2152# define RTAsn1GeneralString_Init                       RT_MANGLER(RTAsn1GeneralString_Init)
     2153# define RTAsn1GraphicString_CheckSanity                RT_MANGLER(RTAsn1GraphicString_CheckSanity)
     2154# define RTAsn1GraphicString_Clone                      RT_MANGLER(RTAsn1GraphicString_Clone)
     2155# define RTAsn1GraphicString_Compare                    RT_MANGLER(RTAsn1GraphicString_Compare)
     2156# define RTAsn1GraphicString_Delete                     RT_MANGLER(RTAsn1GraphicString_Delete)
     2157# define RTAsn1GraphicString_Enum                       RT_MANGLER(RTAsn1GraphicString_Enum)
     2158# define RTAsn1GraphicString_Init                       RT_MANGLER(RTAsn1GraphicString_Init)
     2159# define RTAsn1Ia5String_CheckSanity                    RT_MANGLER(RTAsn1Ia5String_CheckSanity)
     2160# define RTAsn1Ia5String_Clone                          RT_MANGLER(RTAsn1Ia5String_Clone)
     2161# define RTAsn1Ia5String_Compare                        RT_MANGLER(RTAsn1Ia5String_Compare)
     2162# define RTAsn1Ia5String_Delete                         RT_MANGLER(RTAsn1Ia5String_Delete)
     2163# define RTAsn1Ia5String_Enum                           RT_MANGLER(RTAsn1Ia5String_Enum)
     2164# define RTAsn1Ia5String_Init                           RT_MANGLER(RTAsn1Ia5String_Init)
     2165# define RTAsn1NumericString_CheckSanity                RT_MANGLER(RTAsn1NumericString_CheckSanity)
     2166# define RTAsn1NumericString_Clone                      RT_MANGLER(RTAsn1NumericString_Clone)
     2167# define RTAsn1NumericString_Compare                    RT_MANGLER(RTAsn1NumericString_Compare)
     2168# define RTAsn1NumericString_Delete                     RT_MANGLER(RTAsn1NumericString_Delete)
     2169# define RTAsn1NumericString_Enum                       RT_MANGLER(RTAsn1NumericString_Enum)
     2170# define RTAsn1NumericString_Init                       RT_MANGLER(RTAsn1NumericString_Init)
     2171# define RTAsn1PrintableString_CheckSanity              RT_MANGLER(RTAsn1PrintableString_CheckSanity)
     2172# define RTAsn1PrintableString_Clone                    RT_MANGLER(RTAsn1PrintableString_Clone)
     2173# define RTAsn1PrintableString_Compare                  RT_MANGLER(RTAsn1PrintableString_Compare)
     2174# define RTAsn1PrintableString_Delete                   RT_MANGLER(RTAsn1PrintableString_Delete)
     2175# define RTAsn1PrintableString_Enum                     RT_MANGLER(RTAsn1PrintableString_Enum)
     2176# define RTAsn1PrintableString_Init                     RT_MANGLER(RTAsn1PrintableString_Init)
     2177# define RTAsn1SeqOfStrings_CheckSanity                 RT_MANGLER(RTAsn1SeqOfStrings_CheckSanity)
     2178# define RTAsn1SeqOfStrings_Clone                       RT_MANGLER(RTAsn1SeqOfStrings_Clone)
     2179# define RTAsn1SeqOfStrings_Compare                     RT_MANGLER(RTAsn1SeqOfStrings_Compare)
     2180# define RTAsn1SeqOfStrings_Delete                      RT_MANGLER(RTAsn1SeqOfStrings_Delete)
     2181# define RTAsn1SeqOfStrings_Enum                        RT_MANGLER(RTAsn1SeqOfStrings_Enum)
     2182# define RTAsn1SeqOfStrings_Init                        RT_MANGLER(RTAsn1SeqOfStrings_Init)
     2183# define RTAsn1SetOfStrings_CheckSanity                 RT_MANGLER(RTAsn1SetOfStrings_CheckSanity)
     2184# define RTAsn1SetOfStrings_Clone                       RT_MANGLER(RTAsn1SetOfStrings_Clone)
     2185# define RTAsn1SetOfStrings_Compare                     RT_MANGLER(RTAsn1SetOfStrings_Compare)
     2186# define RTAsn1SetOfStrings_Delete                      RT_MANGLER(RTAsn1SetOfStrings_Delete)
     2187# define RTAsn1SetOfStrings_Enum                        RT_MANGLER(RTAsn1SetOfStrings_Enum)
     2188# define RTAsn1SetOfStrings_Init                        RT_MANGLER(RTAsn1SetOfStrings_Init)
     2189# define RTAsn1String_CheckSanity                       RT_MANGLER(RTAsn1String_CheckSanity)
     2190# define RTAsn1String_Clone                             RT_MANGLER(RTAsn1String_Clone)
     2191# define RTAsn1String_Compare                           RT_MANGLER(RTAsn1String_Compare)
     2192# define RTAsn1String_CompareEx                         RT_MANGLER(RTAsn1String_CompareEx)
     2193# define RTAsn1String_CompareWithString                 RT_MANGLER(RTAsn1String_CompareWithString)
     2194# define RTAsn1String_Delete                            RT_MANGLER(RTAsn1String_Delete)
     2195# define RTAsn1String_Enum                              RT_MANGLER(RTAsn1String_Enum)
     2196# define RTAsn1String_Init                              RT_MANGLER(RTAsn1String_Init)
     2197# define RTAsn1String_InitEx                            RT_MANGLER(RTAsn1String_InitEx)
     2198# define RTAsn1String_InitWithValue                     RT_MANGLER(RTAsn1String_InitWithValue)
     2199# define RTAsn1String_QueryUtf8                         RT_MANGLER(RTAsn1String_QueryUtf8)
     2200# define RTAsn1String_QueryUtf8Len                      RT_MANGLER(RTAsn1String_QueryUtf8Len)
     2201# define RTAsn1String_RecodeAsUtf8                      RT_MANGLER(RTAsn1String_RecodeAsUtf8)
     2202# define RTAsn1T61String_CheckSanity                    RT_MANGLER(RTAsn1T61String_CheckSanity)
     2203# define RTAsn1T61String_Clone                          RT_MANGLER(RTAsn1T61String_Clone)
     2204# define RTAsn1T61String_Compare                        RT_MANGLER(RTAsn1T61String_Compare)
     2205# define RTAsn1T61String_Delete                         RT_MANGLER(RTAsn1T61String_Delete)
     2206# define RTAsn1T61String_Enum                           RT_MANGLER(RTAsn1T61String_Enum)
     2207# define RTAsn1T61String_Init                           RT_MANGLER(RTAsn1T61String_Init)
     2208# define RTAsn1UniversalString_CheckSanity              RT_MANGLER(RTAsn1UniversalString_CheckSanity)
     2209# define RTAsn1UniversalString_Clone                    RT_MANGLER(RTAsn1UniversalString_Clone)
     2210# define RTAsn1UniversalString_Compare                  RT_MANGLER(RTAsn1UniversalString_Compare)
     2211# define RTAsn1UniversalString_Delete                   RT_MANGLER(RTAsn1UniversalString_Delete)
     2212# define RTAsn1UniversalString_Enum                     RT_MANGLER(RTAsn1UniversalString_Enum)
     2213# define RTAsn1UniversalString_Init                     RT_MANGLER(RTAsn1UniversalString_Init)
     2214# define RTAsn1Utf8String_CheckSanity                   RT_MANGLER(RTAsn1Utf8String_CheckSanity)
     2215# define RTAsn1Utf8String_Clone                         RT_MANGLER(RTAsn1Utf8String_Clone)
     2216# define RTAsn1Utf8String_Compare                       RT_MANGLER(RTAsn1Utf8String_Compare)
     2217# define RTAsn1Utf8String_Delete                        RT_MANGLER(RTAsn1Utf8String_Delete)
     2218# define RTAsn1Utf8String_Enum                          RT_MANGLER(RTAsn1Utf8String_Enum)
     2219# define RTAsn1Utf8String_Init                          RT_MANGLER(RTAsn1Utf8String_Init)
     2220# define RTAsn1VisibleString_CheckSanity                RT_MANGLER(RTAsn1VisibleString_CheckSanity)
     2221# define RTAsn1VisibleString_Clone                      RT_MANGLER(RTAsn1VisibleString_Clone)
     2222# define RTAsn1VisibleString_Compare                    RT_MANGLER(RTAsn1VisibleString_Compare)
     2223# define RTAsn1VisibleString_Delete                     RT_MANGLER(RTAsn1VisibleString_Delete)
     2224# define RTAsn1VisibleString_Enum                       RT_MANGLER(RTAsn1VisibleString_Enum)
     2225# define RTAsn1VisibleString_Init                       RT_MANGLER(RTAsn1VisibleString_Init)
     2226# define RTAsn1BmpString_DecodeAsn1                     RT_MANGLER(RTAsn1BmpString_DecodeAsn1)
     2227# define RTAsn1GeneralString_DecodeAsn1                 RT_MANGLER(RTAsn1GeneralString_DecodeAsn1)
     2228# define RTAsn1GraphicString_DecodeAsn1                 RT_MANGLER(RTAsn1GraphicString_DecodeAsn1)
     2229# define RTAsn1Ia5String_DecodeAsn1                     RT_MANGLER(RTAsn1Ia5String_DecodeAsn1)
     2230# define RTAsn1NumericString_DecodeAsn1                 RT_MANGLER(RTAsn1NumericString_DecodeAsn1)
     2231# define RTAsn1PrintableString_DecodeAsn1               RT_MANGLER(RTAsn1PrintableString_DecodeAsn1)
     2232# define RTAsn1SeqOfStrings_DecodeAsn1                  RT_MANGLER(RTAsn1SeqOfStrings_DecodeAsn1)
     2233# define RTAsn1SetOfStrings_DecodeAsn1                  RT_MANGLER(RTAsn1SetOfStrings_DecodeAsn1)
     2234# define RTAsn1String_DecodeAsn1                        RT_MANGLER(RTAsn1String_DecodeAsn1)
     2235# define RTAsn1T61String_DecodeAsn1                     RT_MANGLER(RTAsn1T61String_DecodeAsn1)
     2236# define RTAsn1UniversalString_DecodeAsn1               RT_MANGLER(RTAsn1UniversalString_DecodeAsn1)
     2237# define RTAsn1Utf8String_DecodeAsn1                    RT_MANGLER(RTAsn1Utf8String_DecodeAsn1)
     2238# define RTAsn1VisibleString_DecodeAsn1                 RT_MANGLER(RTAsn1VisibleString_DecodeAsn1)
     2239# define RTAsn1GeneralizedTime_CheckSanity              RT_MANGLER(RTAsn1GeneralizedTime_CheckSanity)
     2240# define RTAsn1GeneralizedTime_Clone                    RT_MANGLER(RTAsn1GeneralizedTime_Clone)
     2241# define RTAsn1GeneralizedTime_Compare                  RT_MANGLER(RTAsn1GeneralizedTime_Compare)
     2242# define RTAsn1GeneralizedTime_Delete                   RT_MANGLER(RTAsn1GeneralizedTime_Delete)
     2243# define RTAsn1GeneralizedTime_Enum                     RT_MANGLER(RTAsn1GeneralizedTime_Enum)
     2244# define RTAsn1GeneralizedTime_Init                     RT_MANGLER(RTAsn1GeneralizedTime_Init)
     2245# define RTAsn1SeqOfTimes_CheckSanity                   RT_MANGLER(RTAsn1SeqOfTimes_CheckSanity)
     2246# define RTAsn1SeqOfTimes_Clone                         RT_MANGLER(RTAsn1SeqOfTimes_Clone)
     2247# define RTAsn1SeqOfTimes_Compare                       RT_MANGLER(RTAsn1SeqOfTimes_Compare)
     2248# define RTAsn1SeqOfTimes_Delete                        RT_MANGLER(RTAsn1SeqOfTimes_Delete)
     2249# define RTAsn1SeqOfTimes_Enum                          RT_MANGLER(RTAsn1SeqOfTimes_Enum)
     2250# define RTAsn1SeqOfTimes_Init                          RT_MANGLER(RTAsn1SeqOfTimes_Init)
     2251# define RTAsn1SetOfTimes_CheckSanity                   RT_MANGLER(RTAsn1SetOfTimes_CheckSanity)
     2252# define RTAsn1SetOfTimes_Clone                         RT_MANGLER(RTAsn1SetOfTimes_Clone)
     2253# define RTAsn1SetOfTimes_Compare                       RT_MANGLER(RTAsn1SetOfTimes_Compare)
     2254# define RTAsn1SetOfTimes_Delete                        RT_MANGLER(RTAsn1SetOfTimes_Delete)
     2255# define RTAsn1SetOfTimes_Enum                          RT_MANGLER(RTAsn1SetOfTimes_Enum)
     2256# define RTAsn1SetOfTimes_Init                          RT_MANGLER(RTAsn1SetOfTimes_Init)
     2257# define RTAsn1Time_CheckSanity                         RT_MANGLER(RTAsn1Time_CheckSanity)
     2258# define RTAsn1Time_Clone                               RT_MANGLER(RTAsn1Time_Clone)
     2259# define RTAsn1Time_Compare                             RT_MANGLER(RTAsn1Time_Compare)
     2260# define RTAsn1Time_CompareWithTimeSpec                 RT_MANGLER(RTAsn1Time_CompareWithTimeSpec)
     2261# define RTAsn1Time_Delete                              RT_MANGLER(RTAsn1Time_Delete)
     2262# define RTAsn1Time_Enum                                RT_MANGLER(RTAsn1Time_Enum)
     2263# define RTAsn1Time_Init                                RT_MANGLER(RTAsn1Time_Init)
     2264# define RTAsn1UtcTime_CheckSanity                      RT_MANGLER(RTAsn1UtcTime_CheckSanity)
     2265# define RTAsn1UtcTime_Clone                            RT_MANGLER(RTAsn1UtcTime_Clone)
     2266# define RTAsn1UtcTime_Compare                          RT_MANGLER(RTAsn1UtcTime_Compare)
     2267# define RTAsn1UtcTime_Delete                           RT_MANGLER(RTAsn1UtcTime_Delete)
     2268# define RTAsn1UtcTime_Enum                             RT_MANGLER(RTAsn1UtcTime_Enum)
     2269# define RTAsn1UtcTime_Init                             RT_MANGLER(RTAsn1UtcTime_Init)
     2270# define RTAsn1GeneralizedTime_DecodeAsn1               RT_MANGLER(RTAsn1GeneralizedTime_DecodeAsn1)
     2271# define RTAsn1SeqOfTimes_DecodeAsn1                    RT_MANGLER(RTAsn1SeqOfTimes_DecodeAsn1)
     2272# define RTAsn1SetOfTimes_DecodeAsn1                    RT_MANGLER(RTAsn1SetOfTimes_DecodeAsn1)
     2273# define RTAsn1Time_DecodeAsn1                          RT_MANGLER(RTAsn1Time_DecodeAsn1)
     2274# define RTAsn1UtcTime_DecodeAsn1                       RT_MANGLER(RTAsn1UtcTime_DecodeAsn1)
     2275# define RTMd2                                          RT_MANGLER(RTMd2)
     2276# define RTMd2Final                                     RT_MANGLER(RTMd2Final)
     2277# define RTMd2Init                                      RT_MANGLER(RTMd2Init)
     2278# define RTMd2Update                                    RT_MANGLER(RTMd2Update)
     2279# define RTMd2FromString                                RT_MANGLER(RTMd2FromString)
     2280# define RTMd2ToString                                  RT_MANGLER(RTMd2ToString)
     2281# define RTCrDigestClone                                RT_MANGLER(RTCrDigestClone)
     2282# define RTCrDigestCreate                               RT_MANGLER(RTCrDigestCreate)
     2283# define RTCrDigestFinal                                RT_MANGLER(RTCrDigestFinal)
     2284# define RTCrDigestGetConsumedSize                      RT_MANGLER(RTCrDigestGetConsumedSize)
     2285# define RTCrDigestGetHash                              RT_MANGLER(RTCrDigestGetHash)
     2286# define RTCrDigestGetHashSize                          RT_MANGLER(RTCrDigestGetHashSize)
     2287# define RTCrDigestGetType                              RT_MANGLER(RTCrDigestGetType)
     2288# define RTCrDigestIsFinalized                          RT_MANGLER(RTCrDigestIsFinalized)
     2289# define RTCrDigestMatch                                RT_MANGLER(RTCrDigestMatch)
     2290# define RTCrDigestRelease                              RT_MANGLER(RTCrDigestRelease)
     2291# define RTCrDigestReset                                RT_MANGLER(RTCrDigestReset)
     2292# define RTCrDigestRetain                               RT_MANGLER(RTCrDigestRetain)
     2293# define RTCrDigestUpdate                               RT_MANGLER(RTCrDigestUpdate)
     2294# define RTCrDigestCreateByObjId                        RT_MANGLER(RTCrDigestCreateByObjId)
     2295# define RTCrDigestCreateByObjIdString                  RT_MANGLER(RTCrDigestCreateByObjIdString)
     2296# define RTCrRsaDigestInfo_DecodeAsn1                   RT_MANGLER(RTCrRsaDigestInfo_DecodeAsn1)
     2297# define RTCrRsaOtherPrimeInfo_DecodeAsn1               RT_MANGLER(RTCrRsaOtherPrimeInfo_DecodeAsn1)
     2298# define RTCrRsaOtherPrimeInfos_DecodeAsn1              RT_MANGLER(RTCrRsaOtherPrimeInfos_DecodeAsn1)
     2299# define RTCrRsaPrivateKey_DecodeAsn1                   RT_MANGLER(RTCrRsaPrivateKey_DecodeAsn1)
     2300# define RTCrRsaPublicKey_DecodeAsn1                    RT_MANGLER(RTCrRsaPublicKey_DecodeAsn1)
     2301# define RTCrRsaDigestInfo_Compare                      RT_MANGLER(RTCrRsaDigestInfo_Compare)
     2302# define RTCrRsaDigestInfo_Delete                       RT_MANGLER(RTCrRsaDigestInfo_Delete)
     2303# define RTCrRsaDigestInfo_Enum                         RT_MANGLER(RTCrRsaDigestInfo_Enum)
     2304# define RTCrRsaOtherPrimeInfo_Compare                  RT_MANGLER(RTCrRsaOtherPrimeInfo_Compare)
     2305# define RTCrRsaOtherPrimeInfo_Delete                   RT_MANGLER(RTCrRsaOtherPrimeInfo_Delete)
     2306# define RTCrRsaOtherPrimeInfo_Enum                     RT_MANGLER(RTCrRsaOtherPrimeInfo_Enum)
     2307# define RTCrRsaOtherPrimeInfos_Compare                 RT_MANGLER(RTCrRsaOtherPrimeInfos_Compare)
     2308# define RTCrRsaOtherPrimeInfos_Delete                  RT_MANGLER(RTCrRsaOtherPrimeInfos_Delete)
     2309# define RTCrRsaOtherPrimeInfos_Enum                    RT_MANGLER(RTCrRsaOtherPrimeInfos_Enum)
     2310# define RTCrRsaPrivateKey_Compare                      RT_MANGLER(RTCrRsaPrivateKey_Compare)
     2311# define RTCrRsaPrivateKey_Delete                       RT_MANGLER(RTCrRsaPrivateKey_Delete)
     2312# define RTCrRsaPrivateKey_Enum                         RT_MANGLER(RTCrRsaPrivateKey_Enum)
     2313# define RTCrRsaPublicKey_Compare                       RT_MANGLER(RTCrRsaPublicKey_Compare)
     2314# define RTCrRsaPublicKey_Delete                        RT_MANGLER(RTCrRsaPublicKey_Delete)
     2315# define RTCrRsaPublicKey_Enum                          RT_MANGLER(RTCrRsaPublicKey_Enum)
     2316# define RTCrRsaDigestInfo_Clone                        RT_MANGLER(RTCrRsaDigestInfo_Clone)
     2317# define RTCrRsaDigestInfo_Init                         RT_MANGLER(RTCrRsaDigestInfo_Init)
     2318# define RTCrRsaOtherPrimeInfo_Clone                    RT_MANGLER(RTCrRsaOtherPrimeInfo_Clone)
     2319# define RTCrRsaOtherPrimeInfo_Init                     RT_MANGLER(RTCrRsaOtherPrimeInfo_Init)
     2320# define RTCrRsaOtherPrimeInfos_Clone                   RT_MANGLER(RTCrRsaOtherPrimeInfos_Clone)
     2321# define RTCrRsaOtherPrimeInfos_Init                    RT_MANGLER(RTCrRsaOtherPrimeInfos_Init)
     2322# define RTCrRsaPrivateKey_Clone                        RT_MANGLER(RTCrRsaPrivateKey_Clone)
     2323# define RTCrRsaPrivateKey_Init                         RT_MANGLER(RTCrRsaPrivateKey_Init)
     2324# define RTCrRsaPublicKey_Clone                         RT_MANGLER(RTCrRsaPublicKey_Clone)
     2325# define RTCrRsaPublicKey_Init                          RT_MANGLER(RTCrRsaPublicKey_Init)
     2326# define RTCrRsaDigestInfo_CheckSanity                  RT_MANGLER(RTCrRsaDigestInfo_CheckSanity)
     2327# define RTCrRsaOtherPrimeInfo_CheckSanity              RT_MANGLER(RTCrRsaOtherPrimeInfo_CheckSanity)
     2328# define RTCrRsaOtherPrimeInfos_CheckSanity             RT_MANGLER(RTCrRsaOtherPrimeInfos_CheckSanity)
     2329# define RTCrRsaPrivateKey_CheckSanity                  RT_MANGLER(RTCrRsaPrivateKey_CheckSanity)
     2330# define RTCrRsaPublicKey_CheckSanity                   RT_MANGLER(RTCrRsaPublicKey_CheckSanity)
     2331# define RTCrPemFreeSections                            RT_MANGLER(RTCrPemFreeSections)
     2332# define RTCrPemReadFile                                RT_MANGLER(RTCrPemReadFile)
     2333# define RTCrPkcs7Attribute_DecodeAsn1                  RT_MANGLER(RTCrPkcs7Attribute_DecodeAsn1)
     2334# define RTCrPkcs7Attributes_DecodeAsn1                 RT_MANGLER(RTCrPkcs7Attributes_DecodeAsn1)
     2335# define RTCrPkcs7ContentInfo_DecodeAsn1                RT_MANGLER(RTCrPkcs7ContentInfo_DecodeAsn1)
     2336# define RTCrPkcs7DigestInfo_DecodeAsn1                 RT_MANGLER(RTCrPkcs7DigestInfo_DecodeAsn1)
     2337# define RTCrPkcs7IssuerAndSerialNumber_DecodeAsn1      RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_DecodeAsn1)
     2338# define RTCrPkcs7SignedData_DecodeAsn1                 RT_MANGLER(RTCrPkcs7SignedData_DecodeAsn1)
     2339# define RTCrPkcs7SignerInfo_DecodeAsn1                 RT_MANGLER(RTCrPkcs7SignerInfo_DecodeAsn1)
     2340# define RTCrPkcs7SignerInfos_DecodeAsn1                RT_MANGLER(RTCrPkcs7SignerInfos_DecodeAsn1)
     2341# define RTCrPkcs7Attribute_Compare                     RT_MANGLER(RTCrPkcs7Attribute_Compare)
     2342# define RTCrPkcs7Attribute_Delete                      RT_MANGLER(RTCrPkcs7Attribute_Delete)
     2343# define RTCrPkcs7Attribute_Enum                        RT_MANGLER(RTCrPkcs7Attribute_Enum)
     2344# define RTCrPkcs7Attributes_Compare                    RT_MANGLER(RTCrPkcs7Attributes_Compare)
     2345# define RTCrPkcs7Attributes_Delete                     RT_MANGLER(RTCrPkcs7Attributes_Delete)
     2346# define RTCrPkcs7Attributes_Enum                       RT_MANGLER(RTCrPkcs7Attributes_Enum)
     2347# define RTCrPkcs7ContentInfo_Compare                   RT_MANGLER(RTCrPkcs7ContentInfo_Compare)
     2348# define RTCrPkcs7ContentInfo_Delete                    RT_MANGLER(RTCrPkcs7ContentInfo_Delete)
     2349# define RTCrPkcs7ContentInfo_Enum                      RT_MANGLER(RTCrPkcs7ContentInfo_Enum)
     2350# define RTCrPkcs7ContentInfo_IsSignedData              RT_MANGLER(RTCrPkcs7ContentInfo_IsSignedData)
     2351# define RTCrPkcs7DigestInfo_Compare                    RT_MANGLER(RTCrPkcs7DigestInfo_Compare)
     2352# define RTCrPkcs7DigestInfo_Delete                     RT_MANGLER(RTCrPkcs7DigestInfo_Delete)
     2353# define RTCrPkcs7DigestInfo_Enum                       RT_MANGLER(RTCrPkcs7DigestInfo_Enum)
     2354# define RTCrPkcs7IssuerAndSerialNumber_Compare         RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_Compare)
     2355# define RTCrPkcs7IssuerAndSerialNumber_Delete          RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_Delete)
     2356# define RTCrPkcs7IssuerAndSerialNumber_Enum            RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_Enum)
     2357# define RTCrPkcs7SignedData_Compare                    RT_MANGLER(RTCrPkcs7SignedData_Compare)
     2358# define RTCrPkcs7SignedData_Delete                     RT_MANGLER(RTCrPkcs7SignedData_Delete)
     2359# define RTCrPkcs7SignedData_Enum                       RT_MANGLER(RTCrPkcs7SignedData_Enum)
     2360# define RTCrPkcs7SignerInfo_Compare                    RT_MANGLER(RTCrPkcs7SignerInfo_Compare)
     2361# define RTCrPkcs7SignerInfo_Delete                     RT_MANGLER(RTCrPkcs7SignerInfo_Delete)
     2362# define RTCrPkcs7SignerInfo_Enum                       RT_MANGLER(RTCrPkcs7SignerInfo_Enum)
     2363# define RTCrPkcs7SignerInfos_Compare                   RT_MANGLER(RTCrPkcs7SignerInfos_Compare)
     2364# define RTCrPkcs7SignerInfos_Delete                    RT_MANGLER(RTCrPkcs7SignerInfos_Delete)
     2365# define RTCrPkcs7SignerInfos_Enum                      RT_MANGLER(RTCrPkcs7SignerInfos_Enum)
     2366# define RTCrPkcs7Attribute_Clone                       RT_MANGLER(RTCrPkcs7Attribute_Clone)
     2367# define RTCrPkcs7Attribute_Init                        RT_MANGLER(RTCrPkcs7Attribute_Init)
     2368# define RTCrPkcs7Attributes_Clone                      RT_MANGLER(RTCrPkcs7Attributes_Clone)
     2369# define RTCrPkcs7Attributes_Init                       RT_MANGLER(RTCrPkcs7Attributes_Init)
     2370# define RTCrPkcs7ContentInfo_Clone                     RT_MANGLER(RTCrPkcs7ContentInfo_Clone)
     2371# define RTCrPkcs7ContentInfo_Init                      RT_MANGLER(RTCrPkcs7ContentInfo_Init)
     2372# define RTCrPkcs7DigestInfo_Clone                      RT_MANGLER(RTCrPkcs7DigestInfo_Clone)
     2373# define RTCrPkcs7DigestInfo_Init                       RT_MANGLER(RTCrPkcs7DigestInfo_Init)
     2374# define RTCrPkcs7IssuerAndSerialNumber_Clone           RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_Clone)
     2375# define RTCrPkcs7IssuerAndSerialNumber_Init            RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_Init)
     2376# define RTCrPkcs7SignedData_Clone                      RT_MANGLER(RTCrPkcs7SignedData_Clone)
     2377# define RTCrPkcs7SignedData_Init                       RT_MANGLER(RTCrPkcs7SignedData_Init)
     2378# define RTCrPkcs7SignerInfo_Clone                      RT_MANGLER(RTCrPkcs7SignerInfo_Clone)
     2379# define RTCrPkcs7SignerInfo_Init                       RT_MANGLER(RTCrPkcs7SignerInfo_Init)
     2380# define RTCrPkcs7SignerInfos_Clone                     RT_MANGLER(RTCrPkcs7SignerInfos_Clone)
     2381# define RTCrPkcs7SignerInfos_Init                      RT_MANGLER(RTCrPkcs7SignerInfos_Init)
     2382# define RTCrPkcs7Attribute_CheckSanity                 RT_MANGLER(RTCrPkcs7Attribute_CheckSanity)
     2383# define RTCrPkcs7Attributes_CheckSanity                RT_MANGLER(RTCrPkcs7Attributes_CheckSanity)
     2384# define RTCrPkcs7ContentInfo_CheckSanity               RT_MANGLER(RTCrPkcs7ContentInfo_CheckSanity)
     2385# define RTCrPkcs7DigestInfo_CheckSanity                RT_MANGLER(RTCrPkcs7DigestInfo_CheckSanity)
     2386# define RTCrPkcs7IssuerAndSerialNumber_CheckSanity     RT_MANGLER(RTCrPkcs7IssuerAndSerialNumber_CheckSanity)
     2387# define RTCrPkcs7SignedData_CheckSanity                RT_MANGLER(RTCrPkcs7SignedData_CheckSanity)
     2388# define RTCrPkcs7SignerInfo_CheckSanity                RT_MANGLER(RTCrPkcs7SignerInfo_CheckSanity)
     2389# define RTCrPkcs7SignerInfos_CheckSanity               RT_MANGLER(RTCrPkcs7SignerInfos_CheckSanity)
     2390# define RTCrPkcs7VerifyCertCallbackCodeSigning         RT_MANGLER(RTCrPkcs7VerifyCertCallbackCodeSigning)
     2391# define RTCrPkcs7VerifyCertCallbackDefault             RT_MANGLER(RTCrPkcs7VerifyCertCallbackDefault)
     2392# define RTCrPkcs7VerifySignedData                      RT_MANGLER(RTCrPkcs7VerifySignedData)
     2393# define RTCrPkixSignatureCreateByObjId                 RT_MANGLER(RTCrPkixSignatureCreateByObjId)
     2394# define RTCrPkixSignatureCreateByObjIdString           RT_MANGLER(RTCrPkixSignatureCreateByObjIdString)
     2395# define RTCrPkixSignatureCreate                        RT_MANGLER(RTCrPkixSignatureCreate)
     2396# define RTCrPkixSignatureRelease                       RT_MANGLER(RTCrPkixSignatureRelease)
     2397# define RTCrPkixSignatureRetain                        RT_MANGLER(RTCrPkixSignatureRetain)
     2398# define RTCrPkixSignatureSign                          RT_MANGLER(RTCrPkixSignatureSign)
     2399# define RTCrPkixSignatureVerify                        RT_MANGLER(RTCrPkixSignatureVerify)
     2400# define RTCrPkixSignatureVerifyBitString               RT_MANGLER(RTCrPkixSignatureVerifyBitString)
     2401# define RTCrPkixSignatureVerifyOctetString             RT_MANGLER(RTCrPkixSignatureVerifyOctetString)
     2402# define RTCrPkixGetCiperOidFromSignatureAlgorithm      RT_MANGLER(RTCrPkixGetCiperOidFromSignatureAlgorithm)
     2403# define RTCrPkixPubKeyVerifySignature                  RT_MANGLER(RTCrPkixPubKeyVerifySignature)
     2404# define RTCrSpcAttributeTypeAndOptionalValue_DecodeAsn1 RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_DecodeAsn1)
     2405# define RTCrSpcIndirectDataContent_DecodeAsn1          RT_MANGLER(RTCrSpcIndirectDataContent_DecodeAsn1)
     2406# define RTCrSpcLink_DecodeAsn1                         RT_MANGLER(RTCrSpcLink_DecodeAsn1)
     2407# define RTCrSpcPeImageData_DecodeAsn1                  RT_MANGLER(RTCrSpcPeImageData_DecodeAsn1)
     2408# define RTCrSpcSerializedObjectAttribute_DecodeAsn1    RT_MANGLER(RTCrSpcSerializedObjectAttribute_DecodeAsn1)
     2409# define RTCrSpcSerializedObjectAttributes_DecodeAsn1   RT_MANGLER(RTCrSpcSerializedObjectAttributes_DecodeAsn1)
     2410# define RTCrSpcSerializedObject_DecodeAsn1             RT_MANGLER(RTCrSpcSerializedObject_DecodeAsn1)
     2411# define RTCrSpcSerializedPageHashesV2_DecodeAsn1       RT_MANGLER(RTCrSpcSerializedPageHashesV2_DecodeAsn1)
     2412# define RTCrSpcString_DecodeAsn1                       RT_MANGLER(RTCrSpcString_DecodeAsn1)
     2413# define RTCrSpcAttributeTypeAndOptionalValue_Compare   RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_Compare)
     2414# define RTCrSpcAttributeTypeAndOptionalValue_Delete    RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_Delete)
     2415# define RTCrSpcAttributeTypeAndOptionalValue_Enum      RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_Enum)
     2416# define RTCrSpcIndirectDataContent_Compare             RT_MANGLER(RTCrSpcIndirectDataContent_Compare)
     2417# define RTCrSpcIndirectDataContent_Delete              RT_MANGLER(RTCrSpcIndirectDataContent_Delete)
     2418# define RTCrSpcIndirectDataContent_Enum                RT_MANGLER(RTCrSpcIndirectDataContent_Enum)
     2419# define RTCrSpcIndirectDataContent_GetPeImageHashesV2  RT_MANGLER(RTCrSpcIndirectDataContent_GetPeImageHashesV2)
     2420# define RTCrSpcLink_Compare                            RT_MANGLER(RTCrSpcLink_Compare)
     2421# define RTCrSpcLink_Delete                             RT_MANGLER(RTCrSpcLink_Delete)
     2422# define RTCrSpcLink_Enum                               RT_MANGLER(RTCrSpcLink_Enum)
     2423# define RTCrSpcPeImageData_Compare                     RT_MANGLER(RTCrSpcPeImageData_Compare)
     2424# define RTCrSpcPeImageData_Delete                      RT_MANGLER(RTCrSpcPeImageData_Delete)
     2425# define RTCrSpcPeImageData_Enum                        RT_MANGLER(RTCrSpcPeImageData_Enum)
     2426# define RTCrSpcSerializedObjectAttribute_Compare       RT_MANGLER(RTCrSpcSerializedObjectAttribute_Compare)
     2427# define RTCrSpcSerializedObjectAttribute_Delete        RT_MANGLER(RTCrSpcSerializedObjectAttribute_Delete)
     2428# define RTCrSpcSerializedObjectAttribute_Enum          RT_MANGLER(RTCrSpcSerializedObjectAttribute_Enum)
     2429# define RTCrSpcSerializedObjectAttributes_Compare      RT_MANGLER(RTCrSpcSerializedObjectAttributes_Compare)
     2430# define RTCrSpcSerializedObjectAttributes_Delete       RT_MANGLER(RTCrSpcSerializedObjectAttributes_Delete)
     2431# define RTCrSpcSerializedObjectAttributes_Enum         RT_MANGLER(RTCrSpcSerializedObjectAttributes_Enum)
     2432# define RTCrSpcSerializedObject_Compare                RT_MANGLER(RTCrSpcSerializedObject_Compare)
     2433# define RTCrSpcSerializedObject_Delete                 RT_MANGLER(RTCrSpcSerializedObject_Delete)
     2434# define RTCrSpcSerializedObject_Enum                   RT_MANGLER(RTCrSpcSerializedObject_Enum)
     2435# define RTCrSpcSerializedPageHashesV2_Compare          RT_MANGLER(RTCrSpcSerializedPageHashesV2_Compare)
     2436# define RTCrSpcSerializedPageHashesV2_Delete           RT_MANGLER(RTCrSpcSerializedPageHashesV2_Delete)
     2437# define RTCrSpcSerializedPageHashesV2_Enum             RT_MANGLER(RTCrSpcSerializedPageHashesV2_Enum)
     2438# define RTCrSpcSerializedPageHashesV2_UpdateDerivedData RT_MANGLER(RTCrSpcSerializedPageHashesV2_UpdateDerivedData)
     2439# define RTCrSpcString_Compare                          RT_MANGLER(RTCrSpcString_Compare)
     2440# define RTCrSpcString_Delete                           RT_MANGLER(RTCrSpcString_Delete)
     2441# define RTCrSpcString_Enum                             RT_MANGLER(RTCrSpcString_Enum)
     2442# define RTCrSpcAttributeTypeAndOptionalValue_Clone     RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_Clone)
     2443# define RTCrSpcAttributeTypeAndOptionalValue_Init      RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_Init)
     2444# define RTCrSpcIndirectDataContent_Clone               RT_MANGLER(RTCrSpcIndirectDataContent_Clone)
     2445# define RTCrSpcIndirectDataContent_Init                RT_MANGLER(RTCrSpcIndirectDataContent_Init)
     2446# define RTCrSpcLink_Clone                              RT_MANGLER(RTCrSpcLink_Clone)
     2447# define RTCrSpcLink_Init                               RT_MANGLER(RTCrSpcLink_Init)
     2448# define RTCrSpcPeImageData_Clone                       RT_MANGLER(RTCrSpcPeImageData_Clone)
     2449# define RTCrSpcPeImageData_Init                        RT_MANGLER(RTCrSpcPeImageData_Init)
     2450# define RTCrSpcSerializedObjectAttribute_Clone         RT_MANGLER(RTCrSpcSerializedObjectAttribute_Clone)
     2451# define RTCrSpcSerializedObjectAttribute_Init          RT_MANGLER(RTCrSpcSerializedObjectAttribute_Init)
     2452# define RTCrSpcSerializedObjectAttributes_Clone        RT_MANGLER(RTCrSpcSerializedObjectAttributes_Clone)
     2453# define RTCrSpcSerializedObjectAttributes_Init         RT_MANGLER(RTCrSpcSerializedObjectAttributes_Init)
     2454# define RTCrSpcSerializedObject_Clone                  RT_MANGLER(RTCrSpcSerializedObject_Clone)
     2455# define RTCrSpcSerializedObject_Init                   RT_MANGLER(RTCrSpcSerializedObject_Init)
     2456# define RTCrSpcSerializedPageHashesV2_Clone            RT_MANGLER(RTCrSpcSerializedPageHashesV2_Clone)
     2457# define RTCrSpcSerializedPageHashesV2_Init             RT_MANGLER(RTCrSpcSerializedPageHashesV2_Init)
     2458# define RTCrSpcString_Clone                            RT_MANGLER(RTCrSpcString_Clone)
     2459# define RTCrSpcString_Init                             RT_MANGLER(RTCrSpcString_Init)
     2460# define RTCrSpcAttributeTypeAndOptionalValue_CheckSanity RT_MANGLER(RTCrSpcAttributeTypeAndOptionalValue_CheckSanity)
     2461# define RTCrSpcIndirectDataContent_CheckSanity         RT_MANGLER(RTCrSpcIndirectDataContent_CheckSanity)
     2462# define RTCrSpcIndirectDataContent_CheckSanityEx       RT_MANGLER(RTCrSpcIndirectDataContent_CheckSanityEx)
     2463# define RTCrSpcLink_CheckSanity                        RT_MANGLER(RTCrSpcLink_CheckSanity)
     2464# define RTCrSpcPeImageData_CheckSanity                 RT_MANGLER(RTCrSpcPeImageData_CheckSanity)
     2465# define RTCrSpcSerializedObjectAttribute_CheckSanity   RT_MANGLER(RTCrSpcSerializedObjectAttribute_CheckSanity)
     2466# define RTCrSpcSerializedObjectAttributes_CheckSanity  RT_MANGLER(RTCrSpcSerializedObjectAttributes_CheckSanity)
     2467# define RTCrSpcSerializedObject_CheckSanity            RT_MANGLER(RTCrSpcSerializedObject_CheckSanity)
     2468# define RTCrSpcSerializedPageHashesV2_CheckSanity      RT_MANGLER(RTCrSpcSerializedPageHashesV2_CheckSanity)
     2469# define RTCrSpcString_CheckSanity                      RT_MANGLER(RTCrSpcString_CheckSanity)
     2470# define RTCrX509AlgorithmIdentifier_DecodeAsn1         RT_MANGLER(RTCrX509AlgorithmIdentifier_DecodeAsn1)
     2471# define RTCrX509AlgorithmIdentifiers_DecodeAsn1        RT_MANGLER(RTCrX509AlgorithmIdentifiers_DecodeAsn1)
     2472# define RTCrX509AttributeTypeAndValue_DecodeAsn1       RT_MANGLER(RTCrX509AttributeTypeAndValue_DecodeAsn1)
     2473# define RTCrX509AttributeTypeAndValues_DecodeAsn1      RT_MANGLER(RTCrX509AttributeTypeAndValues_DecodeAsn1)
     2474# define RTCrX509AuthorityKeyIdentifier_DecodeAsn1      RT_MANGLER(RTCrX509AuthorityKeyIdentifier_DecodeAsn1)
     2475# define RTCrX509BasicConstraints_DecodeAsn1            RT_MANGLER(RTCrX509BasicConstraints_DecodeAsn1)
     2476# define RTCrX509CertificatePolicies_DecodeAsn1         RT_MANGLER(RTCrX509CertificatePolicies_DecodeAsn1)
     2477# define RTCrX509Certificate_DecodeAsn1                 RT_MANGLER(RTCrX509Certificate_DecodeAsn1)
     2478# define RTCrX509Certificates_DecodeAsn1                RT_MANGLER(RTCrX509Certificates_DecodeAsn1)
     2479# define RTCrX509Extension_DecodeAsn1                   RT_MANGLER(RTCrX509Extension_DecodeAsn1)
     2480# define RTCrX509Extension_ExtnValue_DecodeAsn1         RT_MANGLER(RTCrX509Extension_ExtnValue_DecodeAsn1)
     2481# define RTCrX509Extensions_DecodeAsn1                  RT_MANGLER(RTCrX509Extensions_DecodeAsn1)
     2482# define RTCrX509GeneralName_DecodeAsn1                 RT_MANGLER(RTCrX509GeneralName_DecodeAsn1)
     2483# define RTCrX509GeneralNames_DecodeAsn1                RT_MANGLER(RTCrX509GeneralNames_DecodeAsn1)
     2484# define RTCrX509GeneralSubtree_DecodeAsn1              RT_MANGLER(RTCrX509GeneralSubtree_DecodeAsn1)
     2485# define RTCrX509GeneralSubtrees_DecodeAsn1             RT_MANGLER(RTCrX509GeneralSubtrees_DecodeAsn1)
     2486# define RTCrX509NameConstraints_DecodeAsn1             RT_MANGLER(RTCrX509NameConstraints_DecodeAsn1)
     2487# define RTCrX509Name_DecodeAsn1                        RT_MANGLER(RTCrX509Name_DecodeAsn1)
     2488# define RTCrX509OldAuthorityKeyIdentifier_DecodeAsn1   RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_DecodeAsn1)
     2489# define RTCrX509PolicyConstraints_DecodeAsn1           RT_MANGLER(RTCrX509PolicyConstraints_DecodeAsn1)
     2490# define RTCrX509PolicyInformation_DecodeAsn1           RT_MANGLER(RTCrX509PolicyInformation_DecodeAsn1)
     2491# define RTCrX509PolicyMapping_DecodeAsn1               RT_MANGLER(RTCrX509PolicyMapping_DecodeAsn1)
     2492# define RTCrX509PolicyMappings_DecodeAsn1              RT_MANGLER(RTCrX509PolicyMappings_DecodeAsn1)
     2493# define RTCrX509PolicyQualifierInfo_DecodeAsn1         RT_MANGLER(RTCrX509PolicyQualifierInfo_DecodeAsn1)
     2494# define RTCrX509PolicyQualifierInfos_DecodeAsn1        RT_MANGLER(RTCrX509PolicyQualifierInfos_DecodeAsn1)
     2495# define RTCrX509SubjectPublicKeyInfo_DecodeAsn1        RT_MANGLER(RTCrX509SubjectPublicKeyInfo_DecodeAsn1)
     2496# define RTCrX509TbsCertificate_DecodeAsn1              RT_MANGLER(RTCrX509TbsCertificate_DecodeAsn1)
     2497# define RTCrX509Validity_DecodeAsn1                    RT_MANGLER(RTCrX509Validity_DecodeAsn1)
     2498# define RTCrX509CertPathsBuild                         RT_MANGLER(RTCrX509CertPathsBuild)
     2499# define RTCrX509CertPathsCreate                        RT_MANGLER(RTCrX509CertPathsCreate)
     2500# define RTCrX509CertPathsCreateEx                      RT_MANGLER(RTCrX509CertPathsCreateEx)
     2501# define RTCrX509CertPathsDumpAll                       RT_MANGLER(RTCrX509CertPathsDumpAll)
     2502# define RTCrX509CertPathsDumpOne                       RT_MANGLER(RTCrX509CertPathsDumpOne)
     2503# define RTCrX509CertPathsGetPathCount                  RT_MANGLER(RTCrX509CertPathsGetPathCount)
     2504# define RTCrX509CertPathsGetPathLength                 RT_MANGLER(RTCrX509CertPathsGetPathLength)
     2505# define RTCrX509CertPathsGetPathNodeCert               RT_MANGLER(RTCrX509CertPathsGetPathNodeCert)
     2506# define RTCrX509CertPathsGetPathVerifyResult           RT_MANGLER(RTCrX509CertPathsGetPathVerifyResult)
     2507# define RTCrX509CertPathsQueryPathInfo                 RT_MANGLER(RTCrX509CertPathsQueryPathInfo)
     2508# define RTCrX509CertPathsRelease                       RT_MANGLER(RTCrX509CertPathsRelease)
     2509# define RTCrX509CertPathsRetain                        RT_MANGLER(RTCrX509CertPathsRetain)
     2510# define RTCrX509CertPathsSetTrustedStore               RT_MANGLER(RTCrX509CertPathsSetTrustedStore)
     2511# define RTCrX509CertPathsSetUntrustedArray             RT_MANGLER(RTCrX509CertPathsSetUntrustedArray)
     2512# define RTCrX509CertPathsSetUntrustedStore             RT_MANGLER(RTCrX509CertPathsSetUntrustedStore)
     2513# define RTCrX509CertPathsSetValidTime                  RT_MANGLER(RTCrX509CertPathsSetValidTime)
     2514# define RTCrX509CertPathsSetValidTimeSpec              RT_MANGLER(RTCrX509CertPathsSetValidTimeSpec)
     2515# define RTCrX509CertPathsValidateAll                   RT_MANGLER(RTCrX509CertPathsValidateAll)
     2516# define RTCrX509CertPathsValidateOne                   RT_MANGLER(RTCrX509CertPathsValidateOne)
     2517# define RTCrX509AlgorithmIdentifier_Compare            RT_MANGLER(RTCrX509AlgorithmIdentifier_Compare)
     2518# define RTCrX509AlgorithmIdentifier_CompareDigestAndEncryptedDigest RT_MANGLER(RTCrX509AlgorithmIdentifier_CompareDigestAndEncryptedDigest)
     2519# define RTCrX509AlgorithmIdentifier_CompareWithString  RT_MANGLER(RTCrX509AlgorithmIdentifier_CompareWithString)
     2520# define RTCrX509AlgorithmIdentifier_Delete             RT_MANGLER(RTCrX509AlgorithmIdentifier_Delete)
     2521# define RTCrX509AlgorithmIdentifier_Enum               RT_MANGLER(RTCrX509AlgorithmIdentifier_Enum)
     2522# define RTCrX509AlgorithmIdentifier_QueryDigestSize    RT_MANGLER(RTCrX509AlgorithmIdentifier_QueryDigestSize)
     2523# define RTCrX509AlgorithmIdentifier_QueryDigestType    RT_MANGLER(RTCrX509AlgorithmIdentifier_QueryDigestType)
     2524# define RTCrX509AlgorithmIdentifiers_Compare           RT_MANGLER(RTCrX509AlgorithmIdentifiers_Compare)
     2525# define RTCrX509AlgorithmIdentifiers_Delete            RT_MANGLER(RTCrX509AlgorithmIdentifiers_Delete)
     2526# define RTCrX509AlgorithmIdentifiers_Enum              RT_MANGLER(RTCrX509AlgorithmIdentifiers_Enum)
     2527# define RTCrX509AttributeTypeAndValue_Compare          RT_MANGLER(RTCrX509AttributeTypeAndValue_Compare)
     2528# define RTCrX509AttributeTypeAndValue_Delete           RT_MANGLER(RTCrX509AttributeTypeAndValue_Delete)
     2529# define RTCrX509AttributeTypeAndValue_Enum             RT_MANGLER(RTCrX509AttributeTypeAndValue_Enum)
     2530# define RTCrX509AttributeTypeAndValues_Compare         RT_MANGLER(RTCrX509AttributeTypeAndValues_Compare)
     2531# define RTCrX509AttributeTypeAndValues_Delete          RT_MANGLER(RTCrX509AttributeTypeAndValues_Delete)
     2532# define RTCrX509AttributeTypeAndValues_Enum            RT_MANGLER(RTCrX509AttributeTypeAndValues_Enum)
     2533# define RTCrX509AuthorityKeyIdentifier_Compare         RT_MANGLER(RTCrX509AuthorityKeyIdentifier_Compare)
     2534# define RTCrX509AuthorityKeyIdentifier_Delete          RT_MANGLER(RTCrX509AuthorityKeyIdentifier_Delete)
     2535# define RTCrX509AuthorityKeyIdentifier_Enum            RT_MANGLER(RTCrX509AuthorityKeyIdentifier_Enum)
     2536# define RTCrX509BasicConstraints_Compare               RT_MANGLER(RTCrX509BasicConstraints_Compare)
     2537# define RTCrX509BasicConstraints_Delete                RT_MANGLER(RTCrX509BasicConstraints_Delete)
     2538# define RTCrX509BasicConstraints_Enum                  RT_MANGLER(RTCrX509BasicConstraints_Enum)
     2539# define RTCrX509CertificatePolicies_Compare            RT_MANGLER(RTCrX509CertificatePolicies_Compare)
     2540# define RTCrX509CertificatePolicies_Delete             RT_MANGLER(RTCrX509CertificatePolicies_Delete)
     2541# define RTCrX509CertificatePolicies_Enum               RT_MANGLER(RTCrX509CertificatePolicies_Enum)
     2542# define RTCrX509Certificate_Compare                    RT_MANGLER(RTCrX509Certificate_Compare)
     2543# define RTCrX509Certificate_Delete                     RT_MANGLER(RTCrX509Certificate_Delete)
     2544# define RTCrX509Certificate_Enum                       RT_MANGLER(RTCrX509Certificate_Enum)
     2545# define RTCrX509Certificate_IsSelfSigned               RT_MANGLER(RTCrX509Certificate_IsSelfSigned)
     2546# define RTCrX509Certificate_MatchIssuerAndSerialNumber RT_MANGLER(RTCrX509Certificate_MatchIssuerAndSerialNumber)
     2547# define RTCrX509Certificate_MatchSubjectOrAltSubjectByRfc5280 RT_MANGLER(RTCrX509Certificate_MatchSubjectOrAltSubjectByRfc5280)
     2548# define RTCrX509Certificates_Compare                   RT_MANGLER(RTCrX509Certificates_Compare)
     2549# define RTCrX509Certificates_Delete                    RT_MANGLER(RTCrX509Certificates_Delete)
     2550# define RTCrX509Certificates_Enum                      RT_MANGLER(RTCrX509Certificates_Enum)
     2551# define RTCrX509Certificates_FindByIssuerAndSerialNumber RT_MANGLER(RTCrX509Certificates_FindByIssuerAndSerialNumber)
     2552# define RTCrX509Extension_Compare                      RT_MANGLER(RTCrX509Extension_Compare)
     2553# define RTCrX509Extension_Delete                       RT_MANGLER(RTCrX509Extension_Delete)
     2554# define RTCrX509Extension_Enum                         RT_MANGLER(RTCrX509Extension_Enum)
     2555# define RTCrX509Extensions_Compare                     RT_MANGLER(RTCrX509Extensions_Compare)
     2556# define RTCrX509Extensions_Delete                      RT_MANGLER(RTCrX509Extensions_Delete)
     2557# define RTCrX509Extensions_Enum                        RT_MANGLER(RTCrX509Extensions_Enum)
     2558# define RTCrX509GeneralName_Compare                    RT_MANGLER(RTCrX509GeneralName_Compare)
     2559# define RTCrX509GeneralName_ConstraintMatch            RT_MANGLER(RTCrX509GeneralName_ConstraintMatch)
     2560# define RTCrX509GeneralName_Delete                     RT_MANGLER(RTCrX509GeneralName_Delete)
     2561# define RTCrX509GeneralName_Enum                       RT_MANGLER(RTCrX509GeneralName_Enum)
     2562# define RTCrX509GeneralNames_Compare                   RT_MANGLER(RTCrX509GeneralNames_Compare)
     2563# define RTCrX509GeneralNames_Delete                    RT_MANGLER(RTCrX509GeneralNames_Delete)
     2564# define RTCrX509GeneralNames_Enum                      RT_MANGLER(RTCrX509GeneralNames_Enum)
     2565# define RTCrX509GeneralSubtree_Compare                 RT_MANGLER(RTCrX509GeneralSubtree_Compare)
     2566# define RTCrX509GeneralSubtree_ConstraintMatch         RT_MANGLER(RTCrX509GeneralSubtree_ConstraintMatch)
     2567# define RTCrX509GeneralSubtree_Delete                  RT_MANGLER(RTCrX509GeneralSubtree_Delete)
     2568# define RTCrX509GeneralSubtree_Enum                    RT_MANGLER(RTCrX509GeneralSubtree_Enum)
     2569# define RTCrX509GeneralSubtrees_Compare                RT_MANGLER(RTCrX509GeneralSubtrees_Compare)
     2570# define RTCrX509GeneralSubtrees_Delete                 RT_MANGLER(RTCrX509GeneralSubtrees_Delete)
     2571# define RTCrX509GeneralSubtrees_Enum                   RT_MANGLER(RTCrX509GeneralSubtrees_Enum)
     2572# define RTCrX509NameConstraints_Compare                RT_MANGLER(RTCrX509NameConstraints_Compare)
     2573# define RTCrX509NameConstraints_Delete                 RT_MANGLER(RTCrX509NameConstraints_Delete)
     2574# define RTCrX509NameConstraints_Enum                   RT_MANGLER(RTCrX509NameConstraints_Enum)
     2575# define RTCrX509Name_Compare                           RT_MANGLER(RTCrX509Name_Compare)
     2576# define RTCrX509Name_ConstraintMatch                   RT_MANGLER(RTCrX509Name_ConstraintMatch)
     2577# define RTCrX509Name_Delete                            RT_MANGLER(RTCrX509Name_Delete)
     2578# define RTCrX509Name_Enum                              RT_MANGLER(RTCrX509Name_Enum)
     2579# define RTCrX509Name_FormatAsString                    RT_MANGLER(RTCrX509Name_FormatAsString)
     2580# define RTCrX509Name_MatchByRfc5280                    RT_MANGLER(RTCrX509Name_MatchByRfc5280)
     2581# define RTCrX509Name_MatchWithString                   RT_MANGLER(RTCrX509Name_MatchWithString)
     2582# define RTCrX509OldAuthorityKeyIdentifier_Compare      RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_Compare)
     2583# define RTCrX509OldAuthorityKeyIdentifier_Delete       RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_Delete)
     2584# define RTCrX509OldAuthorityKeyIdentifier_Enum         RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_Enum)
     2585# define RTCrX509PolicyConstraints_Compare              RT_MANGLER(RTCrX509PolicyConstraints_Compare)
     2586# define RTCrX509PolicyConstraints_Delete               RT_MANGLER(RTCrX509PolicyConstraints_Delete)
     2587# define RTCrX509PolicyConstraints_Enum                 RT_MANGLER(RTCrX509PolicyConstraints_Enum)
     2588# define RTCrX509PolicyInformation_Compare              RT_MANGLER(RTCrX509PolicyInformation_Compare)
     2589# define RTCrX509PolicyInformation_Delete               RT_MANGLER(RTCrX509PolicyInformation_Delete)
     2590# define RTCrX509PolicyInformation_Enum                 RT_MANGLER(RTCrX509PolicyInformation_Enum)
     2591# define RTCrX509PolicyMapping_Compare                  RT_MANGLER(RTCrX509PolicyMapping_Compare)
     2592# define RTCrX509PolicyMapping_Delete                   RT_MANGLER(RTCrX509PolicyMapping_Delete)
     2593# define RTCrX509PolicyMapping_Enum                     RT_MANGLER(RTCrX509PolicyMapping_Enum)
     2594# define RTCrX509PolicyMappings_Compare                 RT_MANGLER(RTCrX509PolicyMappings_Compare)
     2595# define RTCrX509PolicyMappings_Delete                  RT_MANGLER(RTCrX509PolicyMappings_Delete)
     2596# define RTCrX509PolicyMappings_Enum                    RT_MANGLER(RTCrX509PolicyMappings_Enum)
     2597# define RTCrX509PolicyQualifierInfo_Compare            RT_MANGLER(RTCrX509PolicyQualifierInfo_Compare)
     2598# define RTCrX509PolicyQualifierInfo_Delete             RT_MANGLER(RTCrX509PolicyQualifierInfo_Delete)
     2599# define RTCrX509PolicyQualifierInfo_Enum               RT_MANGLER(RTCrX509PolicyQualifierInfo_Enum)
     2600# define RTCrX509PolicyQualifierInfos_Compare           RT_MANGLER(RTCrX509PolicyQualifierInfos_Compare)
     2601# define RTCrX509PolicyQualifierInfos_Delete            RT_MANGLER(RTCrX509PolicyQualifierInfos_Delete)
     2602# define RTCrX509PolicyQualifierInfos_Enum              RT_MANGLER(RTCrX509PolicyQualifierInfos_Enum)
     2603# define RTCrX509SubjectPublicKeyInfo_Compare           RT_MANGLER(RTCrX509SubjectPublicKeyInfo_Compare)
     2604# define RTCrX509SubjectPublicKeyInfo_Delete            RT_MANGLER(RTCrX509SubjectPublicKeyInfo_Delete)
     2605# define RTCrX509SubjectPublicKeyInfo_Enum              RT_MANGLER(RTCrX509SubjectPublicKeyInfo_Enum)
     2606# define RTCrX509TbsCertificate_Compare                 RT_MANGLER(RTCrX509TbsCertificate_Compare)
     2607# define RTCrX509TbsCertificate_Delete                  RT_MANGLER(RTCrX509TbsCertificate_Delete)
     2608# define RTCrX509TbsCertificate_Enum                    RT_MANGLER(RTCrX509TbsCertificate_Enum)
     2609# define RTCrX509TbsCertificate_ReprocessExtensions     RT_MANGLER(RTCrX509TbsCertificate_ReprocessExtensions)
     2610# define RTCrX509Validity_Compare                       RT_MANGLER(RTCrX509Validity_Compare)
     2611# define RTCrX509Validity_Delete                        RT_MANGLER(RTCrX509Validity_Delete)
     2612# define RTCrX509Validity_Enum                          RT_MANGLER(RTCrX509Validity_Enum)
     2613# define RTCrX509Validity_IsValidAtTimeSpec             RT_MANGLER(RTCrX509Validity_IsValidAtTimeSpec)
     2614# define RTCrX509Certificate_ReadFromFile               RT_MANGLER(RTCrX509Certificate_ReadFromFile)
     2615# define RTCrX509AlgorithmIdentifier_Clone              RT_MANGLER(RTCrX509AlgorithmIdentifier_Clone)
     2616# define RTCrX509AlgorithmIdentifier_Init               RT_MANGLER(RTCrX509AlgorithmIdentifier_Init)
     2617# define RTCrX509AlgorithmIdentifiers_Clone             RT_MANGLER(RTCrX509AlgorithmIdentifiers_Clone)
     2618# define RTCrX509AlgorithmIdentifiers_Init              RT_MANGLER(RTCrX509AlgorithmIdentifiers_Init)
     2619# define RTCrX509AttributeTypeAndValue_Clone            RT_MANGLER(RTCrX509AttributeTypeAndValue_Clone)
     2620# define RTCrX509AttributeTypeAndValue_Init             RT_MANGLER(RTCrX509AttributeTypeAndValue_Init)
     2621# define RTCrX509AttributeTypeAndValues_Clone           RT_MANGLER(RTCrX509AttributeTypeAndValues_Clone)
     2622# define RTCrX509AttributeTypeAndValues_Init            RT_MANGLER(RTCrX509AttributeTypeAndValues_Init)
     2623# define RTCrX509AuthorityKeyIdentifier_Clone           RT_MANGLER(RTCrX509AuthorityKeyIdentifier_Clone)
     2624# define RTCrX509AuthorityKeyIdentifier_Init            RT_MANGLER(RTCrX509AuthorityKeyIdentifier_Init)
     2625# define RTCrX509BasicConstraints_Clone                 RT_MANGLER(RTCrX509BasicConstraints_Clone)
     2626# define RTCrX509BasicConstraints_Init                  RT_MANGLER(RTCrX509BasicConstraints_Init)
     2627# define RTCrX509CertificatePolicies_Clone              RT_MANGLER(RTCrX509CertificatePolicies_Clone)
     2628# define RTCrX509CertificatePolicies_Init               RT_MANGLER(RTCrX509CertificatePolicies_Init)
     2629# define RTCrX509Certificate_Clone                      RT_MANGLER(RTCrX509Certificate_Clone)
     2630# define RTCrX509Certificate_Init                       RT_MANGLER(RTCrX509Certificate_Init)
     2631# define RTCrX509Certificates_Clone                     RT_MANGLER(RTCrX509Certificates_Clone)
     2632# define RTCrX509Certificates_Init                      RT_MANGLER(RTCrX509Certificates_Init)
     2633# define RTCrX509Extension_Clone                        RT_MANGLER(RTCrX509Extension_Clone)
     2634# define RTCrX509Extension_Init                         RT_MANGLER(RTCrX509Extension_Init)
     2635# define RTCrX509Extensions_Clone                       RT_MANGLER(RTCrX509Extensions_Clone)
     2636# define RTCrX509Extensions_Init                        RT_MANGLER(RTCrX509Extensions_Init)
     2637# define RTCrX509GeneralName_Clone                      RT_MANGLER(RTCrX509GeneralName_Clone)
     2638# define RTCrX509GeneralName_Init                       RT_MANGLER(RTCrX509GeneralName_Init)
     2639# define RTCrX509GeneralNames_Clone                     RT_MANGLER(RTCrX509GeneralNames_Clone)
     2640# define RTCrX509GeneralNames_Init                      RT_MANGLER(RTCrX509GeneralNames_Init)
     2641# define RTCrX509GeneralSubtree_Clone                   RT_MANGLER(RTCrX509GeneralSubtree_Clone)
     2642# define RTCrX509GeneralSubtree_Init                    RT_MANGLER(RTCrX509GeneralSubtree_Init)
     2643# define RTCrX509GeneralSubtrees_Clone                  RT_MANGLER(RTCrX509GeneralSubtrees_Clone)
     2644# define RTCrX509GeneralSubtrees_Init                   RT_MANGLER(RTCrX509GeneralSubtrees_Init)
     2645# define RTCrX509NameConstraints_Clone                  RT_MANGLER(RTCrX509NameConstraints_Clone)
     2646# define RTCrX509NameConstraints_Init                   RT_MANGLER(RTCrX509NameConstraints_Init)
     2647# define RTCrX509Name_Clone                             RT_MANGLER(RTCrX509Name_Clone)
     2648# define RTCrX509Name_Init                              RT_MANGLER(RTCrX509Name_Init)
     2649# define RTCrX509Name_RecodeAsUtf8                      RT_MANGLER(RTCrX509Name_RecodeAsUtf8)
     2650# define RTCrX509OldAuthorityKeyIdentifier_Clone        RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_Clone)
     2651# define RTCrX509OldAuthorityKeyIdentifier_Init         RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_Init)
     2652# define RTCrX509PolicyConstraints_Clone                RT_MANGLER(RTCrX509PolicyConstraints_Clone)
     2653# define RTCrX509PolicyConstraints_Init                 RT_MANGLER(RTCrX509PolicyConstraints_Init)
     2654# define RTCrX509PolicyInformation_Clone                RT_MANGLER(RTCrX509PolicyInformation_Clone)
     2655# define RTCrX509PolicyInformation_Init                 RT_MANGLER(RTCrX509PolicyInformation_Init)
     2656# define RTCrX509PolicyMapping_Clone                    RT_MANGLER(RTCrX509PolicyMapping_Clone)
     2657# define RTCrX509PolicyMapping_Init                     RT_MANGLER(RTCrX509PolicyMapping_Init)
     2658# define RTCrX509PolicyMappings_Clone                   RT_MANGLER(RTCrX509PolicyMappings_Clone)
     2659# define RTCrX509PolicyMappings_Init                    RT_MANGLER(RTCrX509PolicyMappings_Init)
     2660# define RTCrX509PolicyQualifierInfo_Clone              RT_MANGLER(RTCrX509PolicyQualifierInfo_Clone)
     2661# define RTCrX509PolicyQualifierInfo_Init               RT_MANGLER(RTCrX509PolicyQualifierInfo_Init)
     2662# define RTCrX509PolicyQualifierInfos_Clone             RT_MANGLER(RTCrX509PolicyQualifierInfos_Clone)
     2663# define RTCrX509PolicyQualifierInfos_Init              RT_MANGLER(RTCrX509PolicyQualifierInfos_Init)
     2664# define RTCrX509SubjectPublicKeyInfo_Clone             RT_MANGLER(RTCrX509SubjectPublicKeyInfo_Clone)
     2665# define RTCrX509SubjectPublicKeyInfo_Init              RT_MANGLER(RTCrX509SubjectPublicKeyInfo_Init)
     2666# define RTCrX509TbsCertificate_Clone                   RT_MANGLER(RTCrX509TbsCertificate_Clone)
     2667# define RTCrX509TbsCertificate_Init                    RT_MANGLER(RTCrX509TbsCertificate_Init)
     2668# define RTCrX509Validity_Clone                         RT_MANGLER(RTCrX509Validity_Clone)
     2669# define RTCrX509Validity_Init                          RT_MANGLER(RTCrX509Validity_Init)
     2670# define RTCrX509AlgorithmIdentifier_CheckSanity        RT_MANGLER(RTCrX509AlgorithmIdentifier_CheckSanity)
     2671# define RTCrX509AlgorithmIdentifiers_CheckSanity       RT_MANGLER(RTCrX509AlgorithmIdentifiers_CheckSanity)
     2672# define RTCrX509AttributeTypeAndValue_CheckSanity      RT_MANGLER(RTCrX509AttributeTypeAndValue_CheckSanity)
     2673# define RTCrX509AttributeTypeAndValues_CheckSanity     RT_MANGLER(RTCrX509AttributeTypeAndValues_CheckSanity)
     2674# define RTCrX509AuthorityKeyIdentifier_CheckSanity     RT_MANGLER(RTCrX509AuthorityKeyIdentifier_CheckSanity)
     2675# define RTCrX509BasicConstraints_CheckSanity           RT_MANGLER(RTCrX509BasicConstraints_CheckSanity)
     2676# define RTCrX509CertificatePolicies_CheckSanity        RT_MANGLER(RTCrX509CertificatePolicies_CheckSanity)
     2677# define RTCrX509Certificate_CheckSanity                RT_MANGLER(RTCrX509Certificate_CheckSanity)
     2678# define RTCrX509Certificates_CheckSanity               RT_MANGLER(RTCrX509Certificates_CheckSanity)
     2679# define RTCrX509Extension_CheckSanity                  RT_MANGLER(RTCrX509Extension_CheckSanity)
     2680# define RTCrX509Extensions_CheckSanity                 RT_MANGLER(RTCrX509Extensions_CheckSanity)
     2681# define RTCrX509GeneralName_CheckSanity                RT_MANGLER(RTCrX509GeneralName_CheckSanity)
     2682# define RTCrX509GeneralNames_CheckSanity               RT_MANGLER(RTCrX509GeneralNames_CheckSanity)
     2683# define RTCrX509GeneralSubtree_CheckSanity             RT_MANGLER(RTCrX509GeneralSubtree_CheckSanity)
     2684# define RTCrX509GeneralSubtrees_CheckSanity            RT_MANGLER(RTCrX509GeneralSubtrees_CheckSanity)
     2685# define RTCrX509NameConstraints_CheckSanity            RT_MANGLER(RTCrX509NameConstraints_CheckSanity)
     2686# define RTCrX509Name_CheckSanity                       RT_MANGLER(RTCrX509Name_CheckSanity)
     2687# define RTCrX509OldAuthorityKeyIdentifier_CheckSanity  RT_MANGLER(RTCrX509OldAuthorityKeyIdentifier_CheckSanity)
     2688# define RTCrX509PolicyConstraints_CheckSanity          RT_MANGLER(RTCrX509PolicyConstraints_CheckSanity)
     2689# define RTCrX509PolicyInformation_CheckSanity          RT_MANGLER(RTCrX509PolicyInformation_CheckSanity)
     2690# define RTCrX509PolicyMapping_CheckSanity              RT_MANGLER(RTCrX509PolicyMapping_CheckSanity)
     2691# define RTCrX509PolicyMappings_CheckSanity             RT_MANGLER(RTCrX509PolicyMappings_CheckSanity)
     2692# define RTCrX509PolicyQualifierInfo_CheckSanity        RT_MANGLER(RTCrX509PolicyQualifierInfo_CheckSanity)
     2693# define RTCrX509PolicyQualifierInfos_CheckSanity       RT_MANGLER(RTCrX509PolicyQualifierInfos_CheckSanity)
     2694# define RTCrX509SubjectPublicKeyInfo_CheckSanity       RT_MANGLER(RTCrX509SubjectPublicKeyInfo_CheckSanity)
     2695# define RTCrX509TbsCertificate_CheckSanity             RT_MANGLER(RTCrX509TbsCertificate_CheckSanity)
     2696# define RTCrX509Validity_CheckSanity                   RT_MANGLER(RTCrX509Validity_CheckSanity)
     2697# define RTCrX509Certificate_VerifySignature            RT_MANGLER(RTCrX509Certificate_VerifySignature)
     2698# define RTCrTafCertPathControls_DecodeAsn1             RT_MANGLER(RTCrTafCertPathControls_DecodeAsn1)
     2699# define RTCrTafTrustAnchorChoice_DecodeAsn1            RT_MANGLER(RTCrTafTrustAnchorChoice_DecodeAsn1)
     2700# define RTCrTafTrustAnchorInfo_DecodeAsn1              RT_MANGLER(RTCrTafTrustAnchorInfo_DecodeAsn1)
     2701# define RTCrTafTrustAnchorList_DecodeAsn1              RT_MANGLER(RTCrTafTrustAnchorList_DecodeAsn1)
     2702# define RTCrTafCertPathControls_Compare                RT_MANGLER(RTCrTafCertPathControls_Compare)
     2703# define RTCrTafCertPathControls_Delete                 RT_MANGLER(RTCrTafCertPathControls_Delete)
     2704# define RTCrTafCertPathControls_Enum                   RT_MANGLER(RTCrTafCertPathControls_Enum)
     2705# define RTCrTafTrustAnchorChoice_Compare               RT_MANGLER(RTCrTafTrustAnchorChoice_Compare)
     2706# define RTCrTafTrustAnchorChoice_Delete                RT_MANGLER(RTCrTafTrustAnchorChoice_Delete)
     2707# define RTCrTafTrustAnchorChoice_Enum                  RT_MANGLER(RTCrTafTrustAnchorChoice_Enum)
     2708# define RTCrTafTrustAnchorInfo_Compare                 RT_MANGLER(RTCrTafTrustAnchorInfo_Compare)
     2709# define RTCrTafTrustAnchorInfo_Delete                  RT_MANGLER(RTCrTafTrustAnchorInfo_Delete)
     2710# define RTCrTafTrustAnchorInfo_Enum                    RT_MANGLER(RTCrTafTrustAnchorInfo_Enum)
     2711# define RTCrTafTrustAnchorList_Compare                 RT_MANGLER(RTCrTafTrustAnchorList_Compare)
     2712# define RTCrTafTrustAnchorList_Delete                  RT_MANGLER(RTCrTafTrustAnchorList_Delete)
     2713# define RTCrTafTrustAnchorList_Enum                    RT_MANGLER(RTCrTafTrustAnchorList_Enum)
     2714# define RTCrTafCertPathControls_Clone                  RT_MANGLER(RTCrTafCertPathControls_Clone)
     2715# define RTCrTafCertPathControls_Init                   RT_MANGLER(RTCrTafCertPathControls_Init)
     2716# define RTCrTafTrustAnchorChoice_Clone                 RT_MANGLER(RTCrTafTrustAnchorChoice_Clone)
     2717# define RTCrTafTrustAnchorChoice_Init                  RT_MANGLER(RTCrTafTrustAnchorChoice_Init)
     2718# define RTCrTafTrustAnchorInfo_Clone                   RT_MANGLER(RTCrTafTrustAnchorInfo_Clone)
     2719# define RTCrTafTrustAnchorInfo_Init                    RT_MANGLER(RTCrTafTrustAnchorInfo_Init)
     2720# define RTCrTafTrustAnchorList_Clone                   RT_MANGLER(RTCrTafTrustAnchorList_Clone)
     2721# define RTCrTafTrustAnchorList_Init                    RT_MANGLER(RTCrTafTrustAnchorList_Init)
     2722# define RTCrTafCertPathControls_CheckSanity            RT_MANGLER(RTCrTafCertPathControls_CheckSanity)
     2723# define RTCrTafTrustAnchorChoice_CheckSanity           RT_MANGLER(RTCrTafTrustAnchorChoice_CheckSanity)
     2724# define RTCrTafTrustAnchorInfo_CheckSanity             RT_MANGLER(RTCrTafTrustAnchorInfo_CheckSanity)
     2725# define RTCrTafTrustAnchorList_CheckSanity             RT_MANGLER(RTCrTafTrustAnchorList_CheckSanity)
     2726# define RTCrCertCtxRelease                             RT_MANGLER(RTCrCertCtxRelease)
     2727# define RTCrCertCtxRetain                              RT_MANGLER(RTCrCertCtxRetain)
     2728# define RTCrStoreCertAddEncoded                        RT_MANGLER(RTCrStoreCertAddEncoded)
     2729# define RTCrStoreCertByIssuerAndSerialNo               RT_MANGLER(RTCrStoreCertByIssuerAndSerialNo)
     2730# define RTCrStoreCertFindAll                           RT_MANGLER(RTCrStoreCertFindAll)
     2731# define RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280 RT_MANGLER(RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280)
     2732# define RTCrStoreCertSearchDestroy                     RT_MANGLER(RTCrStoreCertSearchDestroy)
     2733# define RTCrStoreCertSearchNext                        RT_MANGLER(RTCrStoreCertSearchNext)
     2734# define RTCrStoreConvertToOpenSslCertStack             RT_MANGLER(RTCrStoreConvertToOpenSslCertStack)
     2735# define RTCrStoreConvertToOpenSslCertStore             RT_MANGLER(RTCrStoreConvertToOpenSslCertStore)
     2736# define RTCrStoreRelease                               RT_MANGLER(RTCrStoreRelease)
     2737# define RTCrStoreRetain                                RT_MANGLER(RTCrStoreRetain)
     2738# define RTCrStoreCreateInMem                           RT_MANGLER(RTCrStoreCreateInMem)
     2739# define RTCrStoreCertAddFromFile                       RT_MANGLER(RTCrStoreCertAddFromFile)
     2740# define RTErrInfoAdd                                   RT_MANGLER(RTErrInfoAdd)
     2741# define RTErrInfoAddF                                  RT_MANGLER(RTErrInfoAddF)
     2742# define RTErrInfoAddV                                  RT_MANGLER(RTErrInfoAddV)
     2743# define RTLdrHashImage                                 RT_MANGLER(RTLdrHashImage)
     2744# define RTLdrOpenWithReader                            RT_MANGLER(RTLdrOpenWithReader)
     2745# define RTLdrQueryPropEx                               RT_MANGLER(RTLdrQueryPropEx)
     2746# define RTLdrVerifySignature                           RT_MANGLER(RTLdrVerifySignature)
     2747# define RTBigNumAdd                                    RT_MANGLER(RTBigNumAdd)
     2748# define RTBigNumAssign                                 RT_MANGLER(RTBigNumAssign)
     2749# define RTBigNumBitWidth                               RT_MANGLER(RTBigNumBitWidth)
     2750# define RTBigNumByteWidth                              RT_MANGLER(RTBigNumByteWidth)
     2751# define RTBigNumClone                                  RT_MANGLER(RTBigNumClone)
     2752# define RTBigNumCompare                                RT_MANGLER(RTBigNumCompare)
     2753# define RTBigNumCompareWithS64                         RT_MANGLER(RTBigNumCompareWithS64)
     2754# define RTBigNumCompareWithU64                         RT_MANGLER(RTBigNumCompareWithU64)
     2755# define RTBigNumDestroy                                RT_MANGLER(RTBigNumDestroy)
     2756# define RTBigNumDivide                                 RT_MANGLER(RTBigNumDivide)
     2757# define RTBigNumExponentiate                           RT_MANGLER(RTBigNumExponentiate)
     2758# define RTBigNumInit                                   RT_MANGLER(RTBigNumInit)
     2759# define RTBigNumInitZero                               RT_MANGLER(RTBigNumInitZero)
     2760# define RTBigNumModExp                                 RT_MANGLER(RTBigNumModExp)
     2761# define RTBigNumModulo                                 RT_MANGLER(RTBigNumModulo)
     2762# define RTBigNumMultiply                               RT_MANGLER(RTBigNumMultiply)
     2763# define RTBigNumNegate                                 RT_MANGLER(RTBigNumNegate)
     2764# define RTBigNumNegateThis                             RT_MANGLER(RTBigNumNegateThis)
     2765# define RTBigNumSubtract                               RT_MANGLER(RTBigNumSubtract)
     2766# define RTBigNumToBytesBigEndian                       RT_MANGLER(RTBigNumToBytesBigEndian)
     2767# define RTUtf16Copy                                    RT_MANGLER(RTUtf16Copy)
     2768# define RTUtf16CopyAscii                               RT_MANGLER(RTUtf16CopyAscii)
     2769# define RTUtf16Cat                                     RT_MANGLER(RTUtf16Cat)
     2770# define RTUtf16CatAscii                                RT_MANGLER(RTUtf16CatAscii)
     2771# define RTUtf16End                                     RT_MANGLER(RTUtf16End)
     2772# define RTUtf16ICmpAscii                               RT_MANGLER(RTUtf16ICmpAscii)
     2773# define RTUtf16NLen                                    RT_MANGLER(RTUtf16NLen)
     2774# define RTUtf16NLenEx                                  RT_MANGLER(RTUtf16NLenEx)
     2775# define RTUtf16PrintHexBytes                           RT_MANGLER(RTUtf16PrintHexBytes)
     2776# define RTMemSaferAllocZExTag                          RT_MANGLER(RTMemSaferAllocZExTag)
     2777# define RTMemSaferAllocZTag                            RT_MANGLER(RTMemSaferAllocZTag)
     2778# define RTMemSaferFree                                 RT_MANGLER(RTMemSaferFree)
     2779# define RTMemSaferReallocZExTag                        RT_MANGLER(RTMemSaferReallocZExTag)
     2780# define RTMemSaferReallocZTag                          RT_MANGLER(RTMemSaferReallocZTag)
     2781# define RTMemSaferScramble                             RT_MANGLER(RTMemSaferScramble)
     2782# define RTMemSaferUnscramble                           RT_MANGLER(RTMemSaferUnscramble)
     2783# define RTErrConvertFromDarwin                         RT_MANGLER(RTErrConvertFromDarwin)
     2784# define RTErrConvertFromDarwinCOM                      RT_MANGLER(RTErrConvertFromDarwinCOM)
     2785# define RTErrConvertFromDarwinIO                       RT_MANGLER(RTErrConvertFromDarwinIO)
     2786# define RTErrConvertFromDarwinKern                     RT_MANGLER(RTErrConvertFromDarwinKern)
     2787# define RTErrConvertFromDarwin                         RT_MANGLER(RTErrConvertFromDarwin)
     2788# define RTErrConvertFromDarwinIO                       RT_MANGLER(RTErrConvertFromDarwinIO)
     2789# define RTErrConvertFromDarwinKern                     RT_MANGLER(RTErrConvertFromDarwinKern)
     2790
    19102791/*
    19112792 * Stable variables (alphabetical order):
     
    19272808# define g_u32RTAssertLine                              RT_MANGLER(g_u32RTAssertLine)
    19282809
     2810/* sort/merge into the above later: */
     2811# define g_RTAsn1Time_Vtable                            RT_MANGLER(g_RTAsn1Time_Vtable)
     2812# define g_RTAsn1String_Vtable                          RT_MANGLER(g_RTAsn1String_Vtable)
     2813# define g_RTAsn1OctetString_Vtable                     RT_MANGLER(g_RTAsn1OctetString_Vtable)
     2814# define g_RTAsn1ObjId_Vtable                           RT_MANGLER(g_RTAsn1ObjId_Vtable)
     2815# define g_RTAsn1Null_Vtable                            RT_MANGLER(g_RTAsn1Null_Vtable)
     2816# define g_RTAsn1Integer_Vtable                         RT_MANGLER(g_RTAsn1Integer_Vtable)
     2817# define g_RTAsn1Core_Vtable                            RT_MANGLER(g_RTAsn1Core_Vtable)
     2818# define g_RTAsn1Boolean_Vtable                         RT_MANGLER(g_RTAsn1Boolean_Vtable)
     2819# define g_RTAsn1BitString_Vtable                       RT_MANGLER(g_RTAsn1BitString_Vtable)
     2820# define g_RTAsn1DefaultAllocator                       RT_MANGLER(g_RTAsn1DefaultAllocator)
    19292821
    19302822
  • trunk/include/iprt/manifest.h

    r48934 r51770  
    5858/** @} */
    5959
    60 /** @name Digest types. */
    61 typedef enum RTDIGESTTYPE
    62 {
    63     /** Invalid digest value.  */
    64     RTDIGESTTYPE_INVALID = 0,
    65     /** CRC32 checksum. */
    66     RTDIGESTTYPE_CRC32,
    67     /** CRC64 checksum. */
    68     RTDIGESTTYPE_CRC64,
    69     /** MD5 checksum (unsafe!). */
    70     RTDIGESTTYPE_MD5,
    71     /** SHA1 checksum (unsafe!). */
    72     RTDIGESTTYPE_SHA1,
    73     /** SHA256 checksum. */
    74     RTDIGESTTYPE_SHA256,
    75     /** SHA512 checksum. */
    76     RTDIGESTTYPE_SHA512,
    77     /** Usual 32-bit type blowup. */
    78     RTDIGESTTYPE_32BIT_HACK = 0x7fffffff
    79 } RTDIGESTTYPE;
    80 /** @} */
    81 
    8260
    8361/**
  • trunk/include/iprt/nt/nt.h

    r49150 r51770  
    55
    66/*
    7  * Copyright (C) 2010-2013 Oracle Corporation
     7 * Copyright (C) 2010-2014 Oracle Corporation
    88 *
    99 * This file is part of VirtualBox Open Source Edition (OSE), as
     
    2828#define ___iprt_nt_nt_h___
    2929
     30/** @def IPRT_NT_MAP_TO_ZW
     31 * Map Nt calls to Zw calls.  In ring-0 the Zw calls let you pass kernel memory
     32 * to the APIs (takes care of the previous context checks).
     33 */
     34#ifdef DOXYGEN_RUNNING
     35# define IPRT_NT_MAP_TO_ZW
     36#endif
     37
     38#ifdef IPRT_NT_MAP_TO_ZW
     39# define NtQueryInformationFile         ZwQueryInformationFile
     40# define NtQueryInformationProcess      ZwQueryInformationProcess
     41# define NtQueryInformationThread       ZwQueryInformationThread
     42# define NtQuerySystemInformation       ZwQuerySystemInformation
     43# define NtClose                        ZwClose
     44# define NtCreateFile                   ZwCreateFile
     45# define NtReadFile                     ZwReadFile
     46# define NtWriteFile                    ZwWriteFile
     47/** @todo this is very incomplete! */
     48#endif
     49
    3050#include <ntstatus.h>
     51
     52/*
     53 * Hacks common to both base header sets.
     54 */
     55#define NtQueryObject              Incomplete_NtQueryObject
     56#define ZwQueryObject              Incomplete_ZwQueryObject
     57#define NtSetInformationObject     Incomplete_NtSetInformationObject
     58#define _OBJECT_INFORMATION_CLASS  Incomplete_OBJECT_INFORMATION_CLASS
     59#define OBJECT_INFORMATION_CLASS   Incomplete_OBJECT_INFORMATION_CLASS
     60#define ObjectBasicInformation     Incomplete_ObjectBasicInformation
     61#define ObjectTypeInformation      Incomplete_ObjectTypeInformation
     62
     63
    3164#ifdef IPRT_NT_USE_WINTERNL
     65/*
     66 * Use Winternl.h.
     67 */
     68# define _FILE_INFORMATION_CLASS                IncompleteWinternl_FILE_INFORMATION_CLASS
     69# define FILE_INFORMATION_CLASS                 IncompleteWinternl_FILE_INFORMATION_CLASS
     70# define FileDirectoryInformation               IncompleteWinternl_FileDirectoryInformation
     71
     72# define NtQueryInformationProcess              IncompleteWinternl_NtQueryInformationProcess
     73# define NtSetInformationProcess                IncompleteWinternl_NtSetInformationProcess
     74# define PROCESSINFOCLASS                       IncompleteWinternl_PROCESSINFOCLASS
     75# define _PROCESSINFOCLASS                      IncompleteWinternl_PROCESSINFOCLASS
     76# define PROCESS_BASIC_INFORMATION              IncompleteWinternl_PROCESS_BASIC_INFORMATION
     77# define PPROCESS_BASIC_INFORMATION             IncompleteWinternl_PPROCESS_BASIC_INFORMATION
     78# define _PROCESS_BASIC_INFORMATION             IncompleteWinternl_PROCESS_BASIC_INFORMATION
     79# define ProcessBasicInformation                IncompleteWinternl_ProcessBasicInformation
     80# define ProcessDebugPort                       IncompleteWinternl_ProcessDebugPort
     81# define ProcessWow64Information                IncompleteWinternl_ProcessWow64Information
     82# define ProcessImageFileName                   IncompleteWinternl_ProcessImageFileName
     83# define ProcessBreakOnTermination              IncompleteWinternl_ProcessBreakOnTermination
     84
     85# define NtQueryInformationThread               IncompleteWinternl_NtQueryInformationThread
     86# define NtSetInformationThread                 IncompleteWinternl_NtSetInformationThread
     87# define THREADINFOCLASS                        IncompleteWinternl_THREADINFOCLASS
     88# define _THREADINFOCLASS                       IncompleteWinternl_THREADINFOCLASS
     89# define ThreadIsIoPending                      IncompleteWinternl_ThreadIsIoPending
     90
     91# define NtQuerySystemInformation               IncompleteWinternl_NtQuerySystemInformation
     92# define NtSetSystemInformation                 IncompleteWinternl_NtSetSystemInformation
     93# define SYSTEM_INFORMATION_CLASS               IncompleteWinternl_SYSTEM_INFORMATION_CLASS
     94# define _SYSTEM_INFORMATION_CLASS              IncompleteWinternl_SYSTEM_INFORMATION_CLASS
     95# define SystemBasicInformation                 IncompleteWinternl_SystemBasicInformation
     96# define SystemPerformanceInformation           IncompleteWinternl_SystemPerformanceInformation
     97# define SystemTimeOfDayInformation             IncompleteWinternl_SystemTimeOfDayInformation
     98# define SystemProcessInformation               IncompleteWinternl_SystemProcessInformation
     99# define SystemProcessorPerformanceInformation  IncompleteWinternl_SystemProcessorPerformanceInformation
     100# define SystemInterruptInformation             IncompleteWinternl_SystemInterruptInformation
     101# define SystemExceptionInformation             IncompleteWinternl_SystemExceptionInformation
     102# define SystemRegistryQuotaInformation         IncompleteWinternl_SystemRegistryQuotaInformation
     103# define SystemLookasideInformation             IncompleteWinternl_SystemLookasideInformation
     104# define SystemPolicyInformation                IncompleteWinternl_SystemPolicyInformation
     105
     106
    32107# define WIN32_NO_STATUS
    33108# include <windef.h>
     
    36111# undef WIN32_NO_STATUS
    37112# include <ntstatus.h>
    38 # define IPRT_NT_NEED_API_GROUP_1
    39 
    40 #elif defined(IPRT_NT_USE_WDM)
     113
     114
     115# undef _FILE_INFORMATION_CLASS
     116# undef FILE_INFORMATION_CLASS
     117# undef FileDirectoryInformation
     118
     119# undef NtQueryInformationProcess
     120# undef NtSetInformationProcess
     121# undef PROCESSINFOCLASS
     122# undef _PROCESSINFOCLASS
     123# undef PROCESS_BASIC_INFORMATION
     124# undef PPROCESS_BASIC_INFORMATION
     125# undef _PROCESS_BASIC_INFORMATION
     126# undef ProcessBasicInformation
     127# undef ProcessDebugPort
     128# undef ProcessWow64Information
     129# undef ProcessImageFileName
     130# undef ProcessBreakOnTermination
     131
     132# undef NtQueryInformationThread
     133# undef NtSetInformationThread
     134# undef THREADINFOCLASS
     135# undef _THREADINFOCLASS
     136# undef ThreadIsIoPending
     137
     138# undef NtQuerySystemInformation
     139# undef NtSetSystemInformation
     140# undef SYSTEM_INFORMATION_CLASS
     141# undef _SYSTEM_INFORMATION_CLASS
     142# undef SystemBasicInformation
     143# undef SystemPerformanceInformation
     144# undef SystemTimeOfDayInformation
     145# undef SystemProcessInformation
     146# undef SystemProcessorPerformanceInformation
     147# undef SystemInterruptInformation
     148# undef SystemExceptionInformation
     149# undef SystemRegistryQuotaInformation
     150# undef SystemLookasideInformation
     151# undef SystemPolicyInformation
     152
     153#else
     154/*
     155 * Use ntifs.h and wdm.h.
     156 */
     157# ifdef RT_ARCH_X86
     158#  define _InterlockedAddLargeStatistic  _InterlockedAddLargeStatistic_StupidDDKVsCompilerCrap
     159#  pragma warning(disable : 4163)
     160# endif
     161
     162# include <ntifs.h>
    41163# include <wdm.h>
    42 # define IPRT_NT_NEED_API_GROUP_1
    43 
    44 #else
    45 # include <ntifs.h>
    46 #endif
     164
     165# ifdef RT_ARCH_X86
     166#  pragma warning(default : 4163)
     167#  undef _InterlockedAddLargeStatistic
     168# endif
     169
     170# define IPRT_NT_NEED_API_GROUP_NTIFS
     171#endif
     172
     173#undef NtQueryObject
     174#undef ZwQueryObject
     175#undef NtSetInformationObject
     176#undef _OBJECT_INFORMATION_CLASS
     177#undef OBJECT_INFORMATION_CLASS
     178#undef ObjectBasicInformation
     179#undef ObjectTypeInformation
     180
    47181#include <iprt/types.h>
    48182
     
    67201                          PHANDLE phHandle, PULONG_PTR puDisposition);
    68202RTDECL(int) RTNtPathOpenDir(const char *pszPath, ACCESS_MASK fDesiredAccess, ULONG fShareAccess, ULONG fCreateOptions,
    69                      ULONG fObjAttribs, PHANDLE phHandle, bool *pfObjDir);
     203                            ULONG fObjAttribs, PHANDLE phHandle, bool *pfObjDir);
    70204RTDECL(int) RTNtPathClose(HANDLE hHandle);
    71205
     
    78212RT_C_DECLS_BEGIN
    79213
    80 #ifdef IPRT_NT_NEED_API_GROUP_1
     214/** @name Process access rights missing in ntddk headers
     215 * @{ */
     216#ifndef  PROCESS_TERMINATE
     217# define PROCESS_TERMINATE                  UINT32_C(0x00000001)
     218#endif
     219#ifndef  PROCESS_CREATE_THREAD
     220# define PROCESS_CREATE_THREAD              UINT32_C(0x00000002)
     221#endif
     222#ifndef  PROCESS_SET_SESSIONID
     223# define PROCESS_SET_SESSIONID              UINT32_C(0x00000004)
     224#endif
     225#ifndef  PROCESS_VM_OPERATION
     226# define PROCESS_VM_OPERATION               UINT32_C(0x00000008)
     227#endif
     228#ifndef  PROCESS_VM_READ
     229# define PROCESS_VM_READ                    UINT32_C(0x00000010)
     230#endif
     231#ifndef  PROCESS_VM_WRITE
     232# define PROCESS_VM_WRITE                   UINT32_C(0x00000020)
     233#endif
     234#ifndef  PROCESS_DUP_HANDLE
     235# define PROCESS_DUP_HANDLE                 UINT32_C(0x00000040)
     236#endif
     237#ifndef  PROCESS_CREATE_PROCESS
     238# define PROCESS_CREATE_PROCESS             UINT32_C(0x00000080)
     239#endif
     240#ifndef  PROCESS_SET_QUOTA
     241# define PROCESS_SET_QUOTA                  UINT32_C(0x00000100)
     242#endif
     243#ifndef  PROCESS_SET_INFORMATION
     244# define PROCESS_SET_INFORMATION            UINT32_C(0x00000200)
     245#endif
     246#ifndef  PROCESS_QUERY_INFORMATION
     247# define PROCESS_QUERY_INFORMATION          UINT32_C(0x00000400)
     248#endif
     249#ifndef  PROCESS_SUSPEND_RESUME
     250# define PROCESS_SUSPEND_RESUME             UINT32_C(0x00000800)
     251#endif
     252#ifndef  PROCESS_QUERY_LIMITED_INFORMATION
     253# define PROCESS_QUERY_LIMITED_INFORMATION  UINT32_C(0x00001000)
     254#endif
     255#ifndef  PROCESS_SET_LIMITED_INFORMATION
     256# define PROCESS_SET_LIMITED_INFORMATION    UINT32_C(0x00002000)
     257#endif
     258#define PROCESS_UNKNOWN_4000                UINT32_C(0x00004000)
     259#define PROCESS_UNKNOWN_6000                UINT32_C(0x00008000)
     260#ifndef PROCESS_ALL_ACCESS
     261# define PROCESS_ALL_ACCESS                 ( STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | UINT32_C(0x0000ffff) )
     262#endif
     263/** @} */
     264
     265/** @name Thread access rights missing in ntddk headers
     266 * @{ */
     267#ifndef THREAD_QUERY_INFORMATION
     268# define THREAD_QUERY_INFORMATION           UINT32_C(0x00000040)
     269#endif
     270#ifndef THREAD_SET_THREAD_TOKEN
     271# define THREAD_SET_THREAD_TOKEN            UINT32_C(0x00000080)
     272#endif
     273#ifndef THREAD_IMPERSONATE
     274# define THREAD_IMPERSONATE                 UINT32_C(0x00000100)
     275#endif
     276#ifndef THREAD_DIRECT_IMPERSONATION
     277# define THREAD_DIRECT_IMPERSONATION        UINT32_C(0x00000200)
     278#endif
     279#ifndef THREAD_RESUME
     280# define THREAD_RESUME                      UINT32_C(0x00001000)
     281#endif
     282#define THREAD_UNKNOWN_2000                 UINT32_C(0x00002000)
     283#define THREAD_UNKNOWN_4000                 UINT32_C(0x00004000)
     284#define THREAD_UNKNOWN_8000                 UINT32_C(0x00008000)
     285/** @} */
     286
     287/** @name Special handle values.
     288 * @{ */
     289#ifndef NtCurrentProcess
     290# define NtCurrentProcess()                 ( (HANDLE)-(intptr_t)1 )
     291#endif
     292#ifndef NtCurrentThread
     293# define NtCurrentThread()                  ( (HANDLE)-(intptr_t)2 )
     294#endif
     295#ifndef ZwCurrentProcess
     296# define ZwCurrentProcess()                 NtCurrentProcess()
     297#endif
     298#ifndef ZwCurrentThread
     299# define ZwCurrentThread()                  NtCurrentThread()
     300#endif
     301/** @} */
     302
     303
     304#ifdef IPRT_NT_USE_WINTERNL
     305typedef struct _CLIENT_ID
     306{
     307    HANDLE UniqueProcess;
     308    HANDLE UniqueThread;
     309} CLIENT_ID;
     310typedef CLIENT_ID *PCLIENT_ID;
     311
     312NTSYSAPI NTSTATUS NTAPI NtCreateSection(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES, PLARGE_INTEGER, ULONG, ULONG, HANDLE);
    81313
    82314typedef struct _FILE_FS_ATTRIBUTE_INFORMATION
     
    89321typedef FILE_FS_ATTRIBUTE_INFORMATION *PFILE_FS_ATTRIBUTE_INFORMATION;
    90322
    91 typedef enum
     323NTSYSAPI NTSTATUS NTAPI NtOpenProcessToken(HANDLE, ACCESS_MASK, PHANDLE);
     324NTSYSAPI NTSTATUS NTAPI NtOpenThreadToken(HANDLE, ACCESS_MASK, BOOLEAN, PHANDLE);
     325
     326typedef enum _FSINFOCLASS
    92327{
    93328    FileFsVolumeInformation = 1,
     
    99334    FileFsFullSizeInformation,
    100335    FileFsObjectIdInformation,
     336    FileFsDriverPathInformation,
     337    FileFsVolumeFlagsInformation,
     338    FileFsSectorSizeInformation,
     339    FileFsDataCopyInformation,
    101340    FileFsMaximumInformation
    102341} FS_INFORMATION_CLASS;
    103342typedef FS_INFORMATION_CLASS *PFS_INFORMATION_CLASS;
    104 extern "C" NTSTATUS NTAPI NtQueryVolumeInformationFile(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FS_INFORMATION_CLASS);
    105 
    106 #endif
    107 
    108 NTSTATUS NTAPI NtOpenDirectoryObject(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES);
     343NTSYSAPI NTSTATUS NTAPI NtQueryVolumeInformationFile(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FS_INFORMATION_CLASS);
     344
     345typedef struct _FILE_STANDARD_INFORMATION
     346{
     347    LARGE_INTEGER   AllocationSize;
     348    LARGE_INTEGER   EndOfFile;
     349    ULONG           NumberOfLinks;
     350    BOOLEAN         DeletePending;
     351    BOOLEAN         Directory;
     352} FILE_STANDARD_INFORMATION;
     353typedef FILE_STANDARD_INFORMATION *PFILE_STANDARD_INFORMATION;
     354typedef enum _FILE_INFORMATION_CLASS
     355{
     356    FileDirectoryInformation = 1,
     357    FileFullDirectoryInformation,
     358    FileBothDirectoryInformation,
     359    FileBasicInformation,
     360    FileStandardInformation,
     361    FileInternalInformation,
     362    FileEaInformation,
     363    FileAccessInformation,
     364    FileNameInformation,
     365    FileRenameInformation,
     366    FileLinkInformation,
     367    FileNamesInformation,
     368    FileDispositionInformation,
     369    FilePositionInformation,
     370    FileFullEaInformation,
     371    FileModeInformation,
     372    FileAlignmentInformation,
     373    FileAllInformation,
     374    FileAllocationInformation,
     375    FileEndOfFileInformation,
     376    FileAlternateNameInformation,
     377    FileStreamInformation,
     378    FilePipeInformation,
     379    FilePipeLocalInformation,
     380    FilePipeRemoteInformation,
     381    FileMailslotQueryInformation,
     382    FileMailslotSetInformation,
     383    FileCompressionInformation,
     384    FileObjectIdInformation,
     385    FileCompletionInformation,
     386    FileMoveClusterInformation,
     387    FileQuotaInformation,
     388    FileReparsePointInformation,
     389    FileNetworkOpenInformation,
     390    FileAttributeTagInformation,
     391    FileTrackingInformation,
     392    FileIdBothDirectoryInformation,
     393    FileIdFullDirectoryInformation,
     394    FileValidDataLengthInformation,
     395    FileShortNameInformation,
     396    FileIoCompletionNotificationInformation,
     397    FileIoStatusBlockRangeInformation,
     398    FileIoPriorityHintInformation,
     399    FileSfioReserveInformation,
     400    FileSfioVolumeInformation,
     401    FileHardLinkInformation,
     402    FileProcessIdsUsingFileInformation,
     403    FileNormalizedNameInformation,
     404    FileNetworkPhysicalNameInformation,
     405    FileIdGlobalTxDirectoryInformation,
     406    FileIsRemoteDeviceInformation,
     407    FileUnusedInformation,
     408    FileNumaNodeInformation,
     409    FileStandardLinkInformation,
     410    FileRemoteProtocolInformation,
     411    FileRenameInformationBypassAccessCheck,
     412    FileLinkInformationBypassAccessCheck,
     413    FileVolumeNameInformation,
     414    FileIdInformation,
     415    FileIdExtdDirectoryInformation,
     416    FileReplaceCompletionInformation,
     417    FileHardLinkFullIdInformation,
     418    FileMaximumInformation
     419} FILE_INFORMATION_CLASS;
     420typedef FILE_INFORMATION_CLASS *PFILE_INFORMATION_CLASS;
     421NTSYSAPI NTSTATUS NTAPI NtQueryInformationFile(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS);
     422
     423typedef struct _MEMORY_SECTION_NAME
     424{
     425    UNICODE_STRING  SectionFileName;
     426    WCHAR           NameBuffer[1];
     427} MEMORY_SECTION_NAME;
     428
     429#ifdef IPRT_NT_USE_WINTERNL
     430typedef struct _PROCESS_BASIC_INFORMATION
     431{
     432    NTSTATUS ExitStatus;
     433    PPEB PebBaseAddress;
     434    ULONG_PTR AffinityMask;
     435    int32_t BasePriority;
     436    ULONG_PTR UniqueProcessId;
     437    ULONG_PTR InheritedFromUniqueProcessId;
     438} PROCESS_BASIC_INFORMATION;
     439typedef PROCESS_BASIC_INFORMATION *PPROCESS_BASIC_INFORMATION;
     440#endif
     441
     442typedef enum _PROCESSINFOCLASS
     443{
     444    ProcessBasicInformation = 0,
     445    ProcessQuotaLimits,
     446    ProcessIoCounters,
     447    ProcessVmCounters,
     448    ProcessTimes,
     449    ProcessBasePriority,
     450    ProcessRaisePriority,
     451    ProcessDebugPort,
     452    ProcessExceptionPort,
     453    ProcessAccessToken,
     454    ProcessLdtInformation,
     455    ProcessLdtSize,
     456    ProcessDefaultHardErrorMode,
     457    ProcessIoPortHandlers,
     458    ProcessPooledUsageAndLimits,
     459    ProcessWorkingSetWatch,
     460    ProcessUserModeIOPL,
     461    ProcessEnableAlignmentFaultFixup,
     462    ProcessPriorityClass,
     463    ProcessWx86Information,
     464    ProcessHandleCount,
     465    ProcessAffinityMask,
     466    ProcessPriorityBoost,
     467    ProcessDeviceMap,
     468    ProcessSessionInformation,
     469    ProcessForegroundInformation,
     470    ProcessWow64Information,
     471    ProcessImageFileName,
     472    ProcessLUIDDeviceMapsEnabled,
     473    ProcessBreakOnTermination,
     474    ProcessDebugObjectHandle,
     475    ProcessDebugFlags,
     476    ProcessHandleTracing,
     477    ProcessIoPriority,
     478    ProcessExecuteFlags,
     479    ProcessTlsInformation,
     480    ProcessCookie,
     481    ProcessImageInformation,
     482    ProcessCycleTime,
     483    ProcessPagePriority,
     484    ProcessInstrumentationCallbak,
     485    ProcessThreadStackAllocation,
     486    ProcessWorkingSetWatchEx,
     487    ProcessImageFileNameWin32,
     488    ProcessImageFileMapping,
     489    ProcessAffinityUpdateMode,
     490    ProcessMemoryAllocationMode,
     491    ProcessGroupInformation,
     492    ProcessTokenVirtualizationEnabled,
     493    ProcessConsoleHostProcess,
     494    ProcessWindowsInformation,
     495    MaxProcessInfoClass
     496} PROCESSINFOCLASS;
     497NTSYSAPI NTSTATUS NTAPI NtQueryInformationProcess(HANDLE, PROCESSINFOCLASS, PVOID, ULONG, PULONG);
     498
     499typedef enum _THREADINFOCLASS
     500{
     501    ThreadBasicInformation = 0,
     502    ThreadTimes,
     503    ThreadPriority,
     504    ThreadBasePriority,
     505    ThreadAffinityMask,
     506    ThreadImpersonationToken,
     507    ThreadDescriptorTableEntry,
     508    ThreadEnableAlignmentFaultFixup,
     509    ThreadEventPair_Reusable,
     510    ThreadQuerySetWin32StartAddress,
     511    ThreadZeroTlsCell,
     512    ThreadPerformanceCount,
     513    ThreadAmILastThread,
     514    ThreadIdealProcessor,
     515    ThreadPriorityBoost,
     516    ThreadSetTlsArrayAddress,
     517    ThreadIsIoPending,
     518    ThreadHideFromDebugger,
     519    ThreadBreakOnTermination,
     520    ThreadSwitchLegacyState,
     521    ThreadIsTerminated,
     522    ThreadLastSystemCall,
     523    ThreadIoPriority,
     524    ThreadCycleTime,
     525    ThreadPagePriority,
     526    ThreadActualBasePriority,
     527    ThreadTebInformation,
     528    ThreadCSwitchMon,
     529    ThreadCSwitchPmu,
     530    ThreadWow64Context,
     531    ThreadGroupInformation,
     532    ThreadUmsInformation,
     533    ThreadCounterProfiling,
     534    ThreadIdealProcessorEx,
     535    ThreadCpuAccountingInformation,
     536    MaxThreadInfoClass
     537} THREADINFOCLASS;
     538NTSYSAPI NTSTATUS NTAPI NtSetInformationThread(HANDLE, THREADINFOCLASS, LPCVOID, ULONG);
     539
     540NTSYSAPI NTSTATUS NTAPI NtQueryInformationToken(HANDLE, TOKEN_INFORMATION_CLASS, PVOID, ULONG, PULONG);
     541
     542NTSYSAPI NTSTATUS NTAPI NtReadFile(HANDLE, HANDLE, PIO_APC_ROUTINE, PVOID, PIO_STATUS_BLOCK, PVOID, ULONG, PLARGE_INTEGER, PULONG);
     543NTSYSAPI NTSTATUS NTAPI NtWriteFile(HANDLE, HANDLE, PIO_APC_ROUTINE, void const *, PIO_STATUS_BLOCK, PVOID, ULONG, PLARGE_INTEGER, PULONG);
     544
     545NTSYSAPI NTSTATUS NTAPI NtReadVirtualMemory(HANDLE, PVOID, PVOID, SIZE_T, PSIZE_T);
     546NTSYSAPI NTSTATUS NTAPI NtWriteVirtualMemory(HANDLE, PVOID, void const *, SIZE_T, PSIZE_T);
     547
     548NTSYSAPI NTSTATUS NTAPI RtlAddAccessAllowedAce(PACL, ULONG, ULONG, PSID);
     549NTSYSAPI NTSTATUS NTAPI RtlCopySid(ULONG, PSID, PSID);
     550NTSYSAPI NTSTATUS NTAPI RtlCreateAcl(PACL, ULONG, ULONG);
     551NTSYSAPI NTSTATUS NTAPI RtlCreateSecurityDescriptor(PSECURITY_DESCRIPTOR, ULONG);
     552NTSYSAPI NTSTATUS NTAPI RtlGetVersion(PRTL_OSVERSIONINFOW);
     553NTSYSAPI NTSTATUS NTAPI RtlInitializeSid(PSID, PSID_IDENTIFIER_AUTHORITY, UCHAR);
     554NTSYSAPI NTSTATUS NTAPI RtlSetDaclSecurityDescriptor(PSECURITY_DESCRIPTOR, BOOLEAN, PACL, BOOLEAN);
     555NTSYSAPI PULONG   NTAPI RtlSubAuthoritySid(PSID, ULONG);
     556
     557#endif /* IPRT_NT_USE_WINTERNL */
     558
     559typedef enum _OBJECT_INFORMATION_CLASS
     560{
     561    ObjectBasicInformation = 0,
     562    ObjectNameInformation,
     563    ObjectTypeInformation,
     564    ObjectAllInformation,
     565    ObjectDataInformation
     566} OBJECT_INFORMATION_CLASS;
     567typedef OBJECT_INFORMATION_CLASS *POBJECT_INFORMATION_CLASS;
     568#ifdef IN_RING0
     569# define NtQueryObject ZwQueryObject
     570#endif
     571NTSYSAPI NTSTATUS NTAPI NtQueryObject(HANDLE, OBJECT_INFORMATION_CLASS, PVOID, ULONG, PULONG);
     572NTSYSAPI NTSTATUS NTAPI NtSetInformationObject(HANDLE, OBJECT_INFORMATION_CLASS, PVOID, ULONG);
     573NTSYSAPI NTSTATUS NTAPI NtDuplicateObject(HANDLE, HANDLE, HANDLE, PHANDLE, ACCESS_MASK, ULONG, ULONG);
     574
     575NTSYSAPI NTSTATUS NTAPI NtOpenDirectoryObject(PHANDLE, ACCESS_MASK, POBJECT_ATTRIBUTES);
    109576
    110577typedef struct _OBJECT_DIRECTORY_INFORMATION
     
    114581} OBJECT_DIRECTORY_INFORMATION;
    115582typedef OBJECT_DIRECTORY_INFORMATION *POBJECT_DIRECTORY_INFORMATION;
    116 
    117 NTSTATUS NTAPI NtQueryDirectoryObject(HANDLE, PVOID, ULONG, BOOLEAN, BOOLEAN, PULONG, PULONG);
     583NTSYSAPI NTSTATUS NTAPI NtQueryDirectoryObject(HANDLE, PVOID, ULONG, BOOLEAN, BOOLEAN, PULONG, PULONG);
     584
     585/** Retured by ProcessImageInformation as well as NtQuerySection. */
     586typedef struct _SECTION_IMAGE_INFORMATION
     587{
     588    PVOID TransferAddress;
     589    ULONG ZeroBits;
     590    SIZE_T MaximumStackSize;
     591    SIZE_T CommittedStackSize;
     592    ULONG SubSystemType;
     593    union
     594    {
     595        struct
     596        {
     597            USHORT SubSystemMinorVersion;
     598            USHORT SubSystemMajorVersion;
     599        };
     600        ULONG SubSystemVersion;
     601    };
     602    ULONG GpValue;
     603    USHORT ImageCharacteristics;
     604    USHORT DllCharacteristics;
     605    USHORT Machine;
     606    BOOLEAN ImageContainsCode;
     607    union /**< Since Vista, used to be a spare BOOLEAN. */
     608    {
     609        struct
     610        {
     611            UCHAR ComPlusNativeRead : 1;
     612            UCHAR ComPlusILOnly : 1;
     613            UCHAR ImageDynamicallyRelocated : 1;
     614            UCHAR ImageMAppedFlat : 1;
     615            UCHAR Reserved : 4;
     616        };
     617        UCHAR ImageFlags;
     618    };
     619    ULONG LoaderFlags;
     620    ULONG ImageFileSize; /**< Since XP? */
     621    ULONG CheckSum; /**< Since Vista, Used to be a reserved/spare ULONG. */
     622} SECTION_IMAGE_INFORMATION;
     623typedef SECTION_IMAGE_INFORMATION *PSECTION_IMAGE_INFORMATION;
     624
     625typedef enum _SECTION_INFORMATION_CLASS
     626{
     627    SectionBasicInformation = 0,
     628    SectionImageInformation,
     629    MaxSectionInfoClass
     630} SECTION_INFORMATION_CLASS;
     631NTSYSAPI NTSTATUS NTAPI NtQuerySection(HANDLE, SECTION_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T);
     632
     633NTSYSAPI NTSTATUS NTAPI NtQueryInformationThread(HANDLE, THREADINFOCLASS, PVOID, ULONG, PULONG);
     634
     635#ifndef SEC_FILE
     636# define SEC_FILE               UINT32_C(0x00800000)
     637#endif
     638#ifndef SEC_IMAGE
     639# define SEC_IMAGE              UINT32_C(0x01000000)
     640#endif
     641#ifndef SEC_PROTECTED_IMAGE
     642# define SEC_PROTECTED_IMAGE    UINT32_C(0x02000000)
     643#endif
     644#ifndef SEC_NOCACHE
     645# define SEC_NOCACHE            UINT32_C(0x10000000)
     646#endif
     647#ifndef MEM_ROTATE
     648# define MEM_ROTATE             UINT32_C(0x00800000)
     649#endif
     650typedef enum _MEMORY_INFORMATION_CLASS
     651{
     652    MemoryBasicInformation = 0,
     653    MemoryWorkingSetList,
     654    MemorySectionName,
     655    MemoryBasicVlmInformation
     656} MEMORY_INFORMATION_CLASS;
     657#ifdef IN_RING0
     658typedef struct _MEMORY_BASIC_INFORMATION
     659{
     660    PVOID BaseAddress;
     661    PVOID AllocationBase;
     662    ULONG AllocationProtect;
     663    SIZE_T RegionSize;
     664    ULONG State;
     665    ULONG Protect;
     666    ULONG Type;
     667} MEMORY_BASIC_INFORMATION;
     668typedef MEMORY_BASIC_INFORMATION *PMEMORY_BASIC_INFORMATION;
     669# define NtQueryVirtualMemory ZwQueryVirtualMemory
     670#endif
     671NTSYSAPI NTSTATUS NTAPI NtQueryVirtualMemory(HANDLE, void const *, MEMORY_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T);
     672
     673typedef enum _SYSTEM_INFORMATION_CLASS
     674{
     675    SystemBasicInformation = 0,
     676    SystemCpuInformation,
     677    SystemPerformanceInformation,
     678    SystemTimeOfDayInformation,
     679    SystemInformation_Unknown_4,
     680    SystemProcessInformation,
     681    SystemInformation_Unknown_6,
     682    SystemInformation_Unknown_7,
     683    SystemProcessorPerformanceInformation,
     684    SystemInformation_Unknown_9,
     685    SystemInformation_Unknown_10,
     686    SystemModuleInformation,
     687    SystemInformation_Unknown_12,
     688    SystemInformation_Unknown_13,
     689    SystemInformation_Unknown_14,
     690    SystemInformation_Unknown_15,
     691    SystemHandleInformation,
     692    SystemInformation_Unknown_17,
     693    SystemPageFileInformation,
     694    SystemInformation_Unknown_19,
     695    SystemInformation_Unknown_20,
     696    SystemCacheInformation,
     697    SystemInformation_Unknown_22,
     698    SystemInterruptInformation,
     699    SystemDpcBehaviourInformation,
     700    SystemFullMemoryInformation,
     701    SystemLoadGdiDriverInformation, /* 26 */
     702    SystemUnloadGdiDriverInformation, /* 27 */
     703    SystemTimeAdjustmentInformation,
     704    SystemSummaryMemoryInformation,
     705    SystemInformation_Unknown_30,
     706    SystemInformation_Unknown_31,
     707    SystemInformation_Unknown_32,
     708    SystemExceptionInformation,
     709    SystemCrashDumpStateInformation,
     710    SystemKernelDebuggerInformation,
     711    SystemContextSwitchInformation,
     712    SystemRegistryQuotaInformation,
     713    SystemInformation_Unknown_38,
     714    SystemInformation_Unknown_39,
     715    SystemInformation_Unknown_40,
     716    SystemInformation_Unknown_41,
     717    SystemInformation_Unknown_42,
     718    SystemInformation_Unknown_43,
     719    SystemCurrentTimeZoneInformation,
     720    SystemLookasideInformation,
     721    SystemSetTimeSlipEvent,
     722    SystemCreateSession,
     723    SystemDeleteSession,
     724    SystemInformation_Unknown_49,
     725    SystemRangeStartInformation,
     726    SystemVerifierInformation,
     727    SystemInformation_Unknown_52,
     728    SystemSessionProcessInformation,
     729    SystemLoadGdiDriverInSystemSpaceInformation, /* 54 */
     730    SystemInformation_Unknown_55,
     731    SystemInformation_Unknown_56,
     732    SystemExtendedProcessInformation,
     733    SystemInformation_Unknown_58,
     734    SystemInformation_Unknown_59,
     735    SystemInformation_Unknown_60,
     736    SystemInformation_Unknown_61,
     737    SystemInformation_Unknown_62,
     738    SystemInformation_Unknown_63,
     739    SystemExtendedHandleInformation, /* 64 */
     740
     741    /** @todo fill gap. they've added a whole bunch of things  */
     742    SystemPolicyInformation = 134,
     743    SystemInformationClassMax
     744} SYSTEM_INFORMATION_CLASS;
     745
     746#ifdef IPRT_NT_USE_WINTERNL
     747typedef struct _VM_COUNTERS
     748{
     749    SIZE_T PeakVirtualSize;
     750    SIZE_T VirtualSize;
     751    ULONG PageFaultCount;
     752    SIZE_T PeakWorkingSetSize;
     753    SIZE_T WorkingSetSize;
     754    SIZE_T QuotaPeakPagedPoolUsage;
     755    SIZE_T QuotaPagedPoolUsage;
     756    SIZE_T QuotaPeakNonPagedPoolUsage;
     757    SIZE_T QuotaNonPagedPoolUsage;
     758    SIZE_T PagefileUsage;
     759    SIZE_T PeakPagefileUsage;
     760} VM_COUNTERS;
     761typedef VM_COUNTERS *PVM_COUNTERS;
     762#endif
     763
     764#if 0
     765typedef struct _IO_COUNTERS
     766{
     767    ULONGLONG ReadOperationCount;
     768    ULONGLONG WriteOperationCount;
     769    ULONGLONG OtherOperationCount;
     770    ULONGLONG ReadTransferCount;
     771    ULONGLONG WriteTransferCount;
     772    ULONGLONG OtherTransferCount;
     773} IO_COUNTERS;
     774typedef IO_COUNTERS *PIO_COUNTERS;
     775#endif
     776
     777typedef struct _RTNT_SYSTEM_PROCESS_INFORMATION
     778{
     779    ULONG NextEntryOffset;          /**< 0x00 / 0x00 */
     780    ULONG NumberOfThreads;          /**< 0x04 / 0x04 */
     781    LARGE_INTEGER Reserved1[3];     /**< 0x08 / 0x08 */
     782    LARGE_INTEGER CreationTime;     /**< 0x20 / 0x20 */
     783    LARGE_INTEGER UserTime;         /**< 0x28 / 0x28 */
     784    LARGE_INTEGER KernelTime;       /**< 0x30 / 0x30 */
     785    UNICODE_STRING ProcessName;     /**< 0x38 / 0x38 Clean unicode encoding? */
     786    int32_t BasePriority;           /**< 0x40 / 0x48 */
     787    HANDLE UniqueProcessId;         /**< 0x44 / 0x50 */
     788    HANDLE ParentProcessId;         /**< 0x48 / 0x58 */
     789    ULONG HandleCount;              /**< 0x4c / 0x60 */
     790    ULONG Reserved2;                /**< 0x50 / 0x64 Session ID? */
     791    ULONG_PTR Reserved3;            /**< 0x54 / 0x68 */
     792    VM_COUNTERS VmCounters;         /**< 0x58 / 0x70 */
     793    IO_COUNTERS IoCounters;         /**< 0x88 / 0xd0 Might not be present in earlier windows versions. */
     794    /* After this follows the threads, then the ProcessName.Buffer. */
     795} RTNT_SYSTEM_PROCESS_INFORMATION;
     796typedef RTNT_SYSTEM_PROCESS_INFORMATION *PRTNT_SYSTEM_PROCESS_INFORMATION;
     797#ifndef IPRT_NT_USE_WINTERNL
     798typedef RTNT_SYSTEM_PROCESS_INFORMATION SYSTEM_PROCESS_INFORMATION ;
     799typedef SYSTEM_PROCESS_INFORMATION *PSYSTEM_PROCESS_INFORMATION;
     800#endif
     801
     802typedef struct _SYSTEM_HANDLE_ENTRY_INFO
     803{
     804    USHORT UniqueProcessId;
     805    USHORT CreatorBackTraceIndex;
     806    UCHAR ObjectTypeIndex;
     807    UCHAR HandleAttributes;
     808    USHORT HandleValue;
     809    PVOID Object;
     810    ULONG GrantedAccess;
     811} SYSTEM_HANDLE_ENTRY_INFO;
     812typedef SYSTEM_HANDLE_ENTRY_INFO *PSYSTEM_HANDLE_ENTRY_INFO;
     813
     814/** Returned by SystemHandleInformation  */
     815typedef struct _SYSTEM_HANDLE_INFORMATION
     816{
     817    ULONG NumberOfHandles;
     818    SYSTEM_HANDLE_ENTRY_INFO Handles[1];
     819} SYSTEM_HANDLE_INFORMATION;
     820typedef SYSTEM_HANDLE_INFORMATION *PSYSTEM_HANDLE_INFORMATION;
     821
     822/** Extended handle information entry.
     823 * @remarks 3 x PVOID + 4 x ULONG = 28 bytes on 32-bit / 40 bytes on 64-bit  */
     824typedef struct _SYSTEM_HANDLE_ENTRY_INFO_EX
     825{
     826    PVOID Object;
     827    HANDLE UniqueProcessId;
     828    HANDLE HandleValue;
     829    ACCESS_MASK GrantedAccess;
     830    USHORT CreatorBackTraceIndex;
     831    USHORT ObjectTypeIndex;
     832    ULONG HandleAttributes;
     833    ULONG Reserved;
     834} SYSTEM_HANDLE_ENTRY_INFO_EX;
     835typedef SYSTEM_HANDLE_ENTRY_INFO_EX *PSYSTEM_HANDLE_ENTRY_INFO_EX;
     836
     837/** Returned by SystemExtendedHandleInformation.  */
     838typedef struct _SYSTEM_HANDLE_INFORMATION_EX
     839{
     840    ULONG_PTR NumberOfHandles;
     841    ULONG_PTR Reserved;
     842    SYSTEM_HANDLE_ENTRY_INFO_EX Handles[1];
     843} SYSTEM_HANDLE_INFORMATION_EX;
     844typedef SYSTEM_HANDLE_INFORMATION_EX *PSYSTEM_HANDLE_INFORMATION_EX;
     845
     846/** Input to SystemSessionProcessInformation. */
     847typedef struct _SYSTEM_SESSION_PROCESS_INFORMATION
     848{
     849    ULONG SessionId;
     850    ULONG BufferLength;
     851    /** Return buffer, SYSTEM_PROCESS_INFORMATION entries. */
     852    PVOID Buffer;
     853} SYSTEM_SESSION_PROCESS_INFORMATION;
     854typedef SYSTEM_SESSION_PROCESS_INFORMATION *PSYSTEM_SESSION_PROCESS_INFORMATION;
     855
     856NTSYSAPI NTSTATUS NTAPI NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG);
     857
     858NTSYSAPI NTSTATUS NTAPI NtDelayExecution(BOOLEAN, PLARGE_INTEGER);
     859NTSYSAPI NTSTATUS NTAPI NtYieldExecution(void);
     860
     861NTSYSAPI NTSTATUS NTAPI RtlAddAccessDeniedAce(PACL, ULONG, ULONG, PSID);
    118862
    119863RT_C_DECLS_END
    120864/** @} */
    121865
    122 #endif
    123 
     866
     867#if defined(IN_RING0) || defined(DOXYGEN_RUNNING)
     868/** @name NT Kernel APIs
     869 * @{ */
     870NTSYSAPI BOOLEAN  NTAPI ObFindHandleForObject(PEPROCESS pProcess, PVOID pvObject, POBJECT_TYPE pObjectType,
     871                                              PVOID pvOptionalConditions, PHANDLE phFound);
     872NTSYSAPI NTSTATUS NTAPI ObReferenceObjectByName(PUNICODE_STRING pObjectPath, ULONG fAttributes, PACCESS_STATE pAccessState,
     873                                                ACCESS_MASK fDesiredAccess, POBJECT_TYPE pObjectType,
     874                                                KPROCESSOR_MODE enmAccessMode, PVOID pvParseContext, PVOID *ppvObject);
     875NTSYSAPI HANDLE   NTAPI PsGetProcessInheritedFromUniqueProcessId(PEPROCESS);
     876NTSYSAPI UCHAR *  NTAPI PsGetProcessImageFileName(PEPROCESS);
     877NTSYSAPI BOOLEAN  NTAPI PsIsProcessBeingDebugged(PEPROCESS);
     878NTSYSAPI ULONG    NTAPI PsGetProcessSessionId(PEPROCESS);
     879extern DECLIMPORT(POBJECT_TYPE *) LpcPortObjectType;            /**< In vista+ this is the ALPC port object type. */
     880extern DECLIMPORT(POBJECT_TYPE *) LpcWaitablePortObjectType;    /**< In vista+ this is the ALPC port object type. */
     881
     882/** @ */
     883#endif /* IN_RING0 */
     884
     885#endif
     886
  • trunk/include/iprt/process.h

    r44528 r51770  
    365365
    366366/**
     367 * Queries the parent process ID.
     368 *
     369 * @returns IPRT status code
     370 * @param   hProcess     The process to query the parent of.
     371 * @param   phParent     Where to return the parent process ID.
     372 */
     373RTR3DECL(int) RTProcQueryParent(RTPROCESS hProcess, PRTPROCESS phParent);
     374
     375/**
    367376 * Query the username of the given process.
    368377 *
  • trunk/include/iprt/stream.h

    r44528 r51770  
    268268
    269269/**
     270 * Dumper vprintf-like function outputting to a stream.
     271 *
     272 * @param   pvUser          The stream to print to.  NULL means standard output.
     273 * @param   pszFormat       Runtime format string.
     274 * @param   va              Arguments specified by pszFormat.
     275 */
     276RTR3DECL(void) RTStrmDumpPrintfV(void *pvUser, const char *pszFormat, va_list va);
     277
     278/**
    270279 * Prints a formatted string to the standard output stream (g_pStdOut).
    271280 *
  • trunk/include/iprt/string.h

    r50793 r51770  
    30103010 * @param   pv          Pointer to the bytes to stringify.
    30113011 * @param   cb          The number of bytes to stringify.
    3012  * @param   fFlags      Must be zero, reserved for future use.
     3012 * @param   fFlags      Combination of RTSTRPRINTHEXBYTES_F_XXX values.
     3013 * @sa      RTUtf16PrintHexBytes.
    30133014 */
    30143015RTDECL(int) RTStrPrintHexBytes(char *pszBuf, size_t cchBuf, void const *pv, size_t cb, uint32_t fFlags);
     3016/** @name RTSTRPRINTHEXBYTES_F_XXX - flags for RTStrPrintHexBytes and RTUtf16PritnHexBytes.
     3017 * @{ */
     3018/** Upper case hex digits, the default is lower case. */
     3019#define RTSTRPRINTHEXBYTES_F_UPPER      RT_BIT(0)
     3020/** @} */
    30153021
    30163022/**
     
    32833289
    32843290/**
     3291 * Find the length of a zero-terminated byte string, given a max string length.
     3292 *
     3293 * @returns The string length or cbMax. The returned length does not include
     3294 *          the zero terminator if it was found.
     3295 *
     3296 * @param   pwszString  The string.
     3297 * @param   cwcMax      The max string length in RTUTF16s.
     3298 * @sa      RTUtf16NLenEx, RTStrNLen.
     3299 */
     3300RTDECL(size_t) RTUtf16NLen(PCRTUTF16 pwszString, size_t cwcMax);
     3301
     3302/**
     3303 * Find the length of a zero-terminated byte string, given
     3304 * a max string length.
     3305 *
     3306 * @returns IPRT status code.
     3307 * @retval  VINF_SUCCESS if the string has a length less than cchMax.
     3308 * @retval  VERR_BUFFER_OVERFLOW if the end of the string wasn't found
     3309 *          before cwcMax was reached.
     3310 *
     3311 * @param   pwszString  The string.
     3312 * @param   cwcMax      The max string length in RTUTF16s.
     3313 * @param   pcwc        Where to store the string length excluding the
     3314 *                      terminator.  This is set to cwcMax if the terminator
     3315 *                      isn't found.
     3316 * @sa      RTUtf16NLen, RTStrNLenEx.
     3317 */
     3318RTDECL(int) RTUtf16NLenEx(PCRTUTF16 pwszString, size_t cwcMax, size_t *pcwc);
     3319
     3320/**
     3321 * Find the zero terminator in a string with a limited length.
     3322 *
     3323 * @returns Pointer to the zero terminator.
     3324 * @returns NULL if the zero terminator was not found.
     3325 *
     3326 * @param   pwszString  The string.
     3327 * @param   cwcMax      The max string length.  RTSTR_MAX is fine.
     3328 */
     3329RTDECL(PCRTUTF16) RTUtf16End(PCRTUTF16 pwszString, size_t cwcMax);
     3330
     3331/**
     3332 * Strips blankspaces from both ends of the string.
     3333 *
     3334 * @returns Pointer to first non-blank char in the string.
     3335 * @param   pwsz    The string to strip.
     3336 */
     3337RTDECL(PRTUTF16) RTUtf16Strip(PRTUTF16 pwsz);
     3338
     3339/**
     3340 * Strips blankspaces from the start of the string.
     3341 *
     3342 * @returns Pointer to first non-blank char in the string.
     3343 * @param   pwsz    The string to strip.
     3344 */
     3345RTDECL(PRTUTF16) RTUtf16StripL(PCRTUTF16 pwsz);
     3346
     3347/**
     3348 * Strips blankspaces from the end of the string.
     3349 *
     3350 * @returns pwsz.
     3351 * @param   pwsz    The string to strip.
     3352 */
     3353RTDECL(PRTUTF16) RTUtf16StripR(PRTUTF16 pwsz);
     3354
     3355/**
     3356 * String copy with overflow handling.
     3357 *
     3358 * @retval  VINF_SUCCESS on success.
     3359 * @retval  VERR_BUFFER_OVERFLOW if the destination buffer is too small.  The
     3360 *          buffer will contain as much of the string as it can hold, fully
     3361 *          terminated.
     3362 *
     3363 * @param   pwszDst             The destination buffer.
     3364 * @param   cwcDst              The size of the destination buffer in RTUTF16s.
     3365 * @param   pwszSrc             The source string.  NULL is not OK.
     3366 */
     3367RTDECL(int) RTUtf16Copy(PRTUTF16 pwszDst, size_t cwcDst, PCRTUTF16 pwszSrc);
     3368
     3369/**
     3370 * String copy with overflow handling, ASCII source.
     3371 *
     3372 * @retval  VINF_SUCCESS on success.
     3373 * @retval  VERR_BUFFER_OVERFLOW if the destination buffer is too small.  The
     3374 *          buffer will contain as much of the string as it can hold, fully
     3375 *          terminated.
     3376 *
     3377 * @param   pwszDst             The destination buffer.
     3378 * @param   cwcDst              The size of the destination buffer in RTUTF16s.
     3379 * @param   pszSrc              The source string, pure ASCII.  NULL is not OK.
     3380 */
     3381RTDECL(int) RTUtf16CopyAscii(PRTUTF16 pwszDst, size_t cwcDst, const char *pszSrc);
     3382
     3383/**
     3384 * String copy with overflow handling.
     3385 *
     3386 * @retval  VINF_SUCCESS on success.
     3387 * @retval  VERR_BUFFER_OVERFLOW if the destination buffer is too small.  The
     3388 *          buffer will contain as much of the string as it can hold, fully
     3389 *          terminated.
     3390 *
     3391 * @param   pwszDst             The destination buffer.
     3392 * @param   cwcDst              The size of the destination buffer in RTUTF16s.
     3393 * @param   pwszSrc             The source string.  NULL is not OK.
     3394 * @param   cwcSrcMax           The maximum number of chars (not code points) to
     3395 *                              copy from the source string, not counting the
     3396 *                              terminator as usual.
     3397 */
     3398RTDECL(int) RTUtf16CopyEx(PRTUTF16 pwszDst, size_t cwcDst, PCRTUTF16 pwszSrc, size_t cwcSrcMax);
     3399
     3400/**
     3401 * String concatenation with overflow handling.
     3402 *
     3403 * @retval  VINF_SUCCESS on success.
     3404 * @retval  VERR_BUFFER_OVERFLOW if the destination buffer is too small.  The
     3405 *          buffer will contain as much of the string as it can hold, fully
     3406 *          terminated.
     3407 *
     3408 * @param   pszDst              The destination buffer.
     3409 * @param   cwcDst              The size of the destination buffer in RTUTF16s.
     3410 * @param   pwszSrc             The source string.  NULL is not OK.
     3411 */
     3412RTDECL(int) RTUtf16Cat(PRTUTF16 pwszDst, size_t cwcDst, PCRTUTF16 pwszSrc);
     3413
     3414/**
     3415 * String concatenation with overflow handling, ASCII source.
     3416 *
     3417 * @retval  VINF_SUCCESS on success.
     3418 * @retval  VERR_BUFFER_OVERFLOW if the destination buffer is too small.  The
     3419 *          buffer will contain as much of the string as it can hold, fully
     3420 *          terminated.
     3421 *
     3422 * @param   pszDst              The destination buffer.
     3423 * @param   cwcDst              The size of the destination buffer in RTUTF16s.
     3424 * @param   pszSrc              The source string, pure ASCII.  NULL is not OK.
     3425 */
     3426RTDECL(int) RTUtf16CatAscii(PRTUTF16 pwszDst, size_t cwcDst, const char *pwszSrc);
     3427
     3428/**
     3429 * String concatenation with overflow handling.
     3430 *
     3431 * @retval  VINF_SUCCESS on success.
     3432 * @retval  VERR_BUFFER_OVERFLOW if the destination buffer is too small.  The
     3433 *          buffer will contain as much of the string as it can hold, fully
     3434 *          terminated.
     3435 *
     3436 * @param   pwszDst             The destination buffer.
     3437 * @param   cwcDst              The size of the destination buffer in RTUTF16s.
     3438 * @param   pwszSrc             The source string.  NULL is not OK.
     3439 * @param   cwcSrcMax           The maximum number of UTF-16 chars (not code
     3440 *                              points) to copy from the source string, not
     3441 *                              counting the terminator as usual.
     3442 */
     3443RTDECL(int) RTUtf16CatEx(PRTUTF16 pwszDst, size_t cwcDst, PCRTUTF16 pwszSrc, size_t cwcSrcMax);
     3444
     3445/**
    32853446 * Performs a case sensitive string compare between two UTF-16 strings.
    32863447 *
     
    32923453 * @remark  This function will not make any attempt to validate the encoding.
    32933454 */
    3294 RTDECL(int) RTUtf16Cmp(register PCRTUTF16 pwsz1, register PCRTUTF16 pwsz2);
     3455RTDECL(int) RTUtf16Cmp(PCRTUTF16 pwsz1, PCRTUTF16 pwsz2);
     3456
     3457/**
     3458 * Performs a case sensitive string compare between an UTF-16 string and a pure
     3459 * ASCII string.
     3460 *
     3461 * @returns < 0 if the first string less than the second string.s
     3462 * @returns 0 if the first string identical to the second string.
     3463 * @returns > 0 if the first string greater than the second string.
     3464 * @param   pwsz1       First UTF-16 string. Null is allowed.
     3465 * @param   psz2        Second string, pure ASCII. Null is allowed.
     3466 * @remark  This function will not make any attempt to validate the encoding.
     3467 */
     3468RTDECL(int) RTUtf16CmpAscii(PCRTUTF16 pwsz1, const char *psz2);
    32953469
    32963470/**
     
    33083482 */
    33093483RTDECL(int) RTUtf16ICmp(PCRTUTF16 pwsz1, PCRTUTF16 pwsz2);
     3484
     3485/**
     3486 * Performs a case insensitive string compare between an UTF-16 string and an
     3487 * pure ASCII string.
     3488 *
     3489 * Since this compare only takes cares about the first 128 codepoints in
     3490 * unicode, no tables are needed and there aren't any real complications.
     3491 *
     3492 * @returns < 0 if the first string less than the second string.
     3493 * @returns 0 if the first string identical to the second string.
     3494 * @returns > 0 if the first string greater than the second string.
     3495 * @param   pwsz1       First UTF-16 string. Null is allowed.
     3496 * @param   psz2        Second string, pure ASCII. Null is allowed.
     3497 */
     3498RTDECL(int) RTUtf16ICmpAscii(PCRTUTF16 pwsz1, const char *psz2);
    33103499
    33113500/**
     
    38033992        && RTUtf16IsLowSurrogate(wcLow);
    38043993}
     3994
     3995/**
     3996 * Formats a buffer stream as hex bytes.
     3997 *
     3998 * The default is no separating spaces or line breaks or anything.
     3999 *
     4000 * @returns IPRT status code.
     4001 * @retval  VERR_INVALID_POINTER if any of the pointers are wrong.
     4002 * @retval  VERR_BUFFER_OVERFLOW if the buffer is insufficent to hold the bytes.
     4003 *
     4004 * @param   pwszBuf     Output string buffer.
     4005 * @param   cwcBuf      The size of the output buffer in RTUTF16 units.
     4006 * @param   pv          Pointer to the bytes to stringify.
     4007 * @param   cb          The number of bytes to stringify.
     4008 * @param   fFlags      Combination of RTSTRPRINTHEXBYTES_F_XXX values.
     4009 * @sa      RTStrPrintHexBytes.
     4010 */
     4011RTDECL(int) RTUtf16PrintHexBytes(PRTUTF16 pwszBuf, size_t cwcBuf, void const *pv, size_t cb, uint32_t fFlags);
    38054012
    38064013/** @} */
     
    39184125/** @} */
    39194126
     4127#ifndef ___iprt_nocrt_string_h
     4128# if defined(RT_OS_WINDOWS)
     4129RTDECL(void *) mempcpy(void *pvDst, const void *pvSrc, size_t cb);
     4130# endif
     4131#endif
     4132
    39204133
    39214134RT_C_DECLS_END
  • trunk/include/iprt/time.h

    r48835 r51770  
    513513    return pTime1->i64NanosecondsRelativeToUnixEpoch == pTime2->i64NanosecondsRelativeToUnixEpoch;
    514514}
     515
     516
     517/**
     518 * Compare two time specs.
     519 *
     520 * @returns 0 if equal, -1 if @a pLeft is smaller, 1 if @a pLeft is larger.
     521 * @returns false they are not equal.
     522 * @param   pLeft       The 1st time spec.
     523 * @param   pRight      The 2nd time spec.
     524 */
     525DECLINLINE(int) RTTimeSpecCompare(PCRTTIMESPEC pLeft, PCRTTIMESPEC pRight)
     526{
     527    if (pLeft->i64NanosecondsRelativeToUnixEpoch == pRight->i64NanosecondsRelativeToUnixEpoch)
     528        return 0;
     529    return pLeft->i64NanosecondsRelativeToUnixEpoch < pRight->i64NanosecondsRelativeToUnixEpoch ? -1 : 1;
     530}
     531
    515532
    516533/**
  • trunk/include/iprt/types.h

    r48932 r51770  
    2929#include <iprt/cdefs.h>
    3030#include <iprt/stdint.h>
     31#include <iprt/stdarg.h>
    3132
    3233/*
     
    736737typedef const struct RTTIMESPEC *PCRTTIMESPEC;
    737738
    738 /**
    739  * Generic pointer union.
    740  */
    741 typedef union RTPTRUNION
    742 {
    743     /** Pointer into the void... */
    744     void                   *pv;
    745     /** Pointer to char value. */
    746     char                   *pch;
    747     /** Pointer to char value. */
    748     unsigned char          *puch;
    749     /** Pointer to a int value. */
    750     int                    *pi;
    751     /** Pointer to a unsigned int value. */
    752     unsigned int           *pu;
    753     /** Pointer to a long value. */
    754     long                   *pl;
    755     /** Pointer to a long value. */
    756     unsigned long          *pul;
    757     /** Pointer to a 8-bit unsigned value. */
    758     uint8_t                *pu8;
    759     /** Pointer to a 16-bit unsigned value. */
    760     uint16_t               *pu16;
    761     /** Pointer to a 32-bit unsigned value. */
    762     uint32_t               *pu32;
    763     /** Pointer to a 64-bit unsigned value. */
    764     uint64_t               *pu64;
    765 } RTPTRUNION;
    766 /** Pointer to a pointer union. */
    767 typedef RTPTRUNION *PRTPTRUNION;
    768 
    769 /**
    770  * Generic const pointer union.
    771  */
    772 typedef union RTCPTRUNION
    773 {
    774     /** Pointer into the void... */
    775     void const             *pv;
    776     /** Pointer to char value. */
    777     char const             *pch;
    778     /** Pointer to char value. */
    779     unsigned char const    *puch;
    780     /** Pointer to a int value. */
    781     int const              *pi;
    782     /** Pointer to a unsigned int value. */
    783     unsigned int const     *pu;
    784     /** Pointer to a long value. */
    785     long const             *pl;
    786     /** Pointer to a long value. */
    787     unsigned long const    *pul;
    788     /** Pointer to a 8-bit unsigned value. */
    789     uint8_t const          *pu8;
    790     /** Pointer to a 16-bit unsigned value. */
    791     uint16_t const         *pu16;
    792     /** Pointer to a 32-bit unsigned value. */
    793     uint32_t const         *pu32;
    794     /** Pointer to a 64-bit unsigned value. */
    795     uint64_t const         *pu64;
    796 } RTCPTRUNION;
    797 /** Pointer to a const pointer union. */
    798 typedef RTCPTRUNION *PRTCPTRUNION;
    799 
    800 /**
    801  * Generic volatile pointer union.
    802  */
    803 typedef union RTVPTRUNION
    804 {
    805     /** Pointer into the void... */
    806     void volatile          *pv;
    807     /** Pointer to char value. */
    808     char volatile          *pch;
    809     /** Pointer to char value. */
    810     unsigned char volatile *puch;
    811     /** Pointer to a int value. */
    812     int volatile           *pi;
    813     /** Pointer to a unsigned int value. */
    814     unsigned int volatile  *pu;
    815     /** Pointer to a long value. */
    816     long volatile          *pl;
    817     /** Pointer to a long value. */
    818     unsigned long volatile *pul;
    819     /** Pointer to a 8-bit unsigned value. */
    820     uint8_t volatile       *pu8;
    821     /** Pointer to a 16-bit unsigned value. */
    822     uint16_t volatile      *pu16;
    823     /** Pointer to a 32-bit unsigned value. */
    824     uint32_t volatile      *pu32;
    825     /** Pointer to a 64-bit unsigned value. */
    826     uint64_t volatile      *pu64;
    827 } RTVPTRUNION;
    828 /** Pointer to a const pointer union. */
    829 typedef RTVPTRUNION *PRTVPTRUNION;
    830 
    831 /**
    832  * Generic const volatile pointer union.
    833  */
    834 typedef union RTCVPTRUNION
    835 {
    836     /** Pointer into the void... */
    837     void const volatile            *pv;
    838     /** Pointer to char value. */
    839     char const volatile            *pch;
    840     /** Pointer to char value. */
    841     unsigned char const volatile   *puch;
    842     /** Pointer to a int value. */
    843     int const volatile             *pi;
    844     /** Pointer to a unsigned int value. */
    845     unsigned int const volatile    *pu;
    846     /** Pointer to a long value. */
    847     long const volatile            *pl;
    848     /** Pointer to a long value. */
    849     unsigned long const volatile   *pul;
    850     /** Pointer to a 8-bit unsigned value. */
    851     uint8_t const volatile         *pu8;
    852     /** Pointer to a 16-bit unsigned value. */
    853     uint16_t const volatile        *pu16;
    854     /** Pointer to a 32-bit unsigned value. */
    855     uint32_t const volatile        *pu32;
    856     /** Pointer to a 64-bit unsigned value. */
    857     uint64_t const volatile        *pu64;
    858 } RTCVPTRUNION;
    859 /** Pointer to a const pointer union. */
    860 typedef RTCVPTRUNION *PRTCVPTRUNION;
    861739
    862740
     
    16371515
    16381516
     1517
     1518/** Pointer to a big integer number. */
     1519typedef struct RTBIGNUM                            *PRTBIGNUM;
     1520/** Pointer to a const big integer number. */
     1521typedef struct RTBIGNUM const                      *PCRTBIGNUM;
     1522
     1523
    16391524/** Pointer to a critical section. */
    16401525typedef struct RTCRITSECT                          *PRTCRITSECT;
     
    16551540#define NIL_RTCONDVAR                               0
    16561541
     1542/** Cryptographic (certificate) store handle. */
     1543typedef R3R0PTRTYPE(struct RTCRSTOREINT *)          RTCRSTORE;
     1544/** Pointer to a Cryptographic (certificate) store handle. */
     1545typedef RTCRSTORE                                  *PRTCRSTORE;
     1546/** Nil Cryptographic (certificate) store handle. */
     1547#define NIL_RTCRSTORE                               0
     1548
     1549/** Pointer to a const (store) certificate context. */
     1550typedef struct RTCRCERTCTX const                   *PCRTCRCERTCTX;
     1551
     1552/** Cryptographic message digest handle. */
     1553typedef R3R0PTRTYPE(struct RTCRDIGESTINT *)         RTCRDIGEST;
     1554/** Pointer to a cryptographic message digest handle. */
     1555typedef RTCRDIGEST                                 *PRTCRDIGEST;
     1556/** NIL cryptographic message digest handle. */
     1557#define NIL_RTCRDIGEST                              (0)
     1558
     1559/** Public key encryption schema handle. */
     1560typedef R3R0PTRTYPE(struct RTCRPKIXENCRYPTIONINT *) RTCRPKIXENCRYPTION;
     1561/** Pointer to a public key encryption schema handle. */
     1562typedef RTCRPKIXENCRYPTION                         *PRTCRPKIXENCRYPTION;
     1563/** NIL publick key encryption schema handle */
     1564#define NIL_RTCRPKIXENCRYPTION                      (0)
     1565
     1566/** Public key signature schema handle. */
     1567typedef R3R0PTRTYPE(struct RTCRPKIXSIGNATUREINT *)  RTCRPKIXSIGNATURE;
     1568/** Pointer to a public key signature schema handle. */
     1569typedef RTCRPKIXSIGNATURE                          *PRTCRPKIXSIGNATURE;
     1570/** NIL publick key signature schema handle */
     1571#define NIL_RTCRPKIXSIGNATURE                       (0)
     1572
     1573/** X.509 certificate paths builder & validator handle. */
     1574typedef R3R0PTRTYPE(struct RTCRX509CERTPATHSINT *)  RTCRX509CERTPATHS;
     1575/** Pointer to a certificate paths builder & validator handle. */
     1576typedef RTCRX509CERTPATHS                          *PRTCRX509CERTPATHS;
     1577/** Nil certificate paths builder & validator handle. */
     1578#define NIL_RTCRX509CERTPATHS                       0
     1579
    16571580/** File handle. */
    16581581typedef R3R0PTRTYPE(struct RTFILEINT *)             RTFILE;
     
    16771600
    16781601/** Loader module handle. */
    1679 typedef R3PTRTYPE(struct RTLDRMODINTERNAL *)        RTLDRMOD;
     1602typedef R3R0PTRTYPE(struct RTLDRMODINTERNAL *)      RTLDRMOD;
    16801603/** Pointer to a loader module handle. */
    16811604typedef RTLDRMOD                                   *PRTLDRMOD;
     
    22542177typedef FNRTPROGRESS *PFNRTPROGRESS;
    22552178
     2179/**
     2180 * Generic vprintf-like callback function for dumpers.
     2181 *
     2182 * @param   pvUser          User argument.
     2183 * @param   pszFormat       The format string.
     2184 * @param   va              Arguments for the format string.
     2185 */
     2186typedef DECLCALLBACK(void) FNRTDUMPPRINTFV(void *pvUser, const char *pszFormat, va_list va);
     2187/** Pointer to a generic printf-like function for dumping. */
     2188typedef FNRTDUMPPRINTFV *PFNRTDUMPPRINTFV;
     2189
    22562190
    22572191/**
     
    23862320
    23872321/**
     2322 * Digest types.
     2323 */
     2324typedef enum RTDIGESTTYPE
     2325{
     2326    /** Invalid digest value.  */
     2327    RTDIGESTTYPE_INVALID = 0,
     2328    /** Unknown digest type. */
     2329    RTDIGESTTYPE_UNKNOWN,
     2330    /** CRC32 checksum. */
     2331    RTDIGESTTYPE_CRC32,
     2332    /** CRC64 checksum. */
     2333    RTDIGESTTYPE_CRC64,
     2334    /** MD2 checksum (unsafe!). */
     2335    RTDIGESTTYPE_MD2,
     2336    /** MD4 checksum (unsafe!!). */
     2337    RTDIGESTTYPE_MD4,
     2338    /** MD5 checksum (unsafe!). */
     2339    RTDIGESTTYPE_MD5,
     2340    /** SHA-1 checksum (unsafe!). */
     2341    RTDIGESTTYPE_SHA1,
     2342    /** SHA-224 checksum. */
     2343    RTDIGESTTYPE_SHA224,
     2344    /** SHA-256 checksum. */
     2345    RTDIGESTTYPE_SHA256,
     2346    /** SHA-384 checksum. */
     2347    RTDIGESTTYPE_SHA384,
     2348    /** SHA-512 checksum. */
     2349    RTDIGESTTYPE_SHA512,
     2350    /** End of valid types. */
     2351    RTDIGESTTYPE_END,
     2352    /** Usual 32-bit type blowup. */
     2353    RTDIGESTTYPE_32BIT_HACK = 0x7fffffff
     2354} RTDIGESTTYPE;
     2355
     2356/**
    23882357 * Process exit codes.
    23892358 */
     
    24222391typedef const RTRANGE *PCRTRANGE;
    24232392
     2393
     2394/**
     2395 * Generic pointer union.
     2396 */
     2397typedef union RTPTRUNION
     2398{
     2399    /** Pointer into the void... */
     2400    void                   *pv;
     2401    /** As a signed integer. */
     2402    intptr_t                i;
     2403    /** As an unsigned integer. */
     2404    intptr_t                u;
     2405    /** Pointer to char value. */
     2406    char                   *pch;
     2407    /** Pointer to char value. */
     2408    unsigned char          *puch;
     2409    /** Pointer to a int value. */
     2410    int                    *pi;
     2411    /** Pointer to a unsigned int value. */
     2412    unsigned int           *pu;
     2413    /** Pointer to a long value. */
     2414    long                   *pl;
     2415    /** Pointer to a long value. */
     2416    unsigned long          *pul;
     2417    /** Pointer to a 8-bit unsigned value. */
     2418    uint8_t                *pu8;
     2419    /** Pointer to a 16-bit unsigned value. */
     2420    uint16_t               *pu16;
     2421    /** Pointer to a 32-bit unsigned value. */
     2422    uint32_t               *pu32;
     2423    /** Pointer to a 64-bit unsigned value. */
     2424    uint64_t               *pu64;
     2425    /** Pointer to a UTF-16 character. */
     2426    PRTUTF16                pwc;
     2427    /** Pointer to a UUID character. */
     2428    PRTUUID                 pUuid;
     2429} RTPTRUNION;
     2430/** Pointer to a pointer union. */
     2431typedef RTPTRUNION *PRTPTRUNION;
     2432
     2433/**
     2434 * Generic const pointer union.
     2435 */
     2436typedef union RTCPTRUNION
     2437{
     2438    /** Pointer into the void... */
     2439    void const             *pv;
     2440    /** As a signed integer. */
     2441    intptr_t                i;
     2442    /** As an unsigned integer. */
     2443    intptr_t                u;
     2444    /** Pointer to char value. */
     2445    char const             *pch;
     2446    /** Pointer to char value. */
     2447    unsigned char const    *puch;
     2448    /** Pointer to a int value. */
     2449    int const              *pi;
     2450    /** Pointer to a unsigned int value. */
     2451    unsigned int const     *pu;
     2452    /** Pointer to a long value. */
     2453    long const             *pl;
     2454    /** Pointer to a long value. */
     2455    unsigned long const    *pul;
     2456    /** Pointer to a 8-bit unsigned value. */
     2457    uint8_t const          *pu8;
     2458    /** Pointer to a 16-bit unsigned value. */
     2459    uint16_t const         *pu16;
     2460    /** Pointer to a 32-bit unsigned value. */
     2461    uint32_t const         *pu32;
     2462    /** Pointer to a 64-bit unsigned value. */
     2463    uint64_t const         *pu64;
     2464    /** Pointer to a UTF-16 character. */
     2465    PCRTUTF16               pwc;
     2466    /** Pointer to a UUID character. */
     2467    PCRTUUID                pUuid;
     2468} RTCPTRUNION;
     2469/** Pointer to a const pointer union. */
     2470typedef RTCPTRUNION *PRTCPTRUNION;
     2471
     2472/**
     2473 * Generic volatile pointer union.
     2474 */
     2475typedef union RTVPTRUNION
     2476{
     2477    /** Pointer into the void... */
     2478    void volatile          *pv;
     2479    /** As a signed integer. */
     2480    intptr_t                i;
     2481    /** As an unsigned integer. */
     2482    intptr_t                u;
     2483    /** Pointer to char value. */
     2484    char volatile          *pch;
     2485    /** Pointer to char value. */
     2486    unsigned char volatile *puch;
     2487    /** Pointer to a int value. */
     2488    int volatile           *pi;
     2489    /** Pointer to a unsigned int value. */
     2490    unsigned int volatile  *pu;
     2491    /** Pointer to a long value. */
     2492    long volatile          *pl;
     2493    /** Pointer to a long value. */
     2494    unsigned long volatile *pul;
     2495    /** Pointer to a 8-bit unsigned value. */
     2496    uint8_t volatile       *pu8;
     2497    /** Pointer to a 16-bit unsigned value. */
     2498    uint16_t volatile      *pu16;
     2499    /** Pointer to a 32-bit unsigned value. */
     2500    uint32_t volatile      *pu32;
     2501    /** Pointer to a 64-bit unsigned value. */
     2502    uint64_t volatile      *pu64;
     2503    /** Pointer to a UTF-16 character. */
     2504    RTUTF16 volatile       *pwc;
     2505    /** Pointer to a UUID character. */
     2506    RTUUID volatile        *pUuid;
     2507} RTVPTRUNION;
     2508/** Pointer to a const pointer union. */
     2509typedef RTVPTRUNION *PRTVPTRUNION;
     2510
     2511/**
     2512 * Generic const volatile pointer union.
     2513 */
     2514typedef union RTCVPTRUNION
     2515{
     2516    /** Pointer into the void... */
     2517    void const volatile            *pv;
     2518    /** As a signed integer. */
     2519    intptr_t                        i;
     2520    /** As an unsigned integer. */
     2521    intptr_t                        u;
     2522    /** Pointer to char value. */
     2523    char const volatile            *pch;
     2524    /** Pointer to char value. */
     2525    unsigned char const volatile   *puch;
     2526    /** Pointer to a int value. */
     2527    int const volatile             *pi;
     2528    /** Pointer to a unsigned int value. */
     2529    unsigned int const volatile    *pu;
     2530    /** Pointer to a long value. */
     2531    long const volatile            *pl;
     2532    /** Pointer to a long value. */
     2533    unsigned long const volatile   *pul;
     2534    /** Pointer to a 8-bit unsigned value. */
     2535    uint8_t const volatile         *pu8;
     2536    /** Pointer to a 16-bit unsigned value. */
     2537    uint16_t const volatile        *pu16;
     2538    /** Pointer to a 32-bit unsigned value. */
     2539    uint32_t const volatile        *pu32;
     2540    /** Pointer to a 64-bit unsigned value. */
     2541    uint64_t const volatile        *pu64;
     2542    /** Pointer to a UTF-16 character. */
     2543    RTUTF16 const volatile         *pwc;
     2544    /** Pointer to a UUID character. */
     2545    RTUUID const volatile          *pUuid;
     2546} RTCVPTRUNION;
     2547/** Pointer to a const pointer union. */
     2548typedef RTCVPTRUNION *PRTCVPTRUNION;
     2549
     2550
     2551
    24242552#ifdef __cplusplus
    24252553/**
  • trunk/include/iprt/uni.h

    r46011 r51770  
    418418
    419419
     420/**
     421 * Checks if a code point valid.
     422 *
     423 * Any code point (defined or not) within the 17 unicode planes (0 thru 16),
     424 * except surrogates will be considered valid code points by this function.
     425 *
     426 * @returns true if in range, false if not.
     427 * @param   CodePoint       The unicode code point to validate.
     428 */
     429DECLINLINE(bool) RTUniCpIsValid(RTUNICP CodePoint)
     430{
     431    return CodePoint <= 0x00d7ff
     432        || (   CodePoint <= 0x10ffff
     433            && CodePoint >= 0x00e000);
     434}
     435
     436
     437/**
     438 * Checks if the given code point is in the BMP range.
     439 *
     440 * Surrogates are not considered in the BMP range by this function.
     441 *
     442 * @returns true if in BMP, false if not.
     443 * @param   CodePoint       The unicode code point to consider.
     444 */
     445DECLINLINE(bool) RTUniCpIsBMP(RTUNICP CodePoint)
     446{
     447    return CodePoint <= 0xd7ff
     448        || (   CodePoint <= 0xffff
     449            && CodePoint >= 0xe000);
     450}
     451
     452
     453/**
     454 * Folds a unicode code point to lower case.
     455 *
     456 * @returns Folded code point.
     457 * @param   CodePoint       The unicode code point to fold.
     458 */
     459DECLINLINE(size_t) RTUniCpCalcUtf8Len(RTUNICP CodePoint)
     460{
     461    if (CodePoint < 0x80)
     462        return 1;
     463    return 2
     464        + (CodePoint >= 0x00000800)
     465        + (CodePoint >= 0x00010000)
     466        + (CodePoint >= 0x00200000)
     467        + (CodePoint >= 0x04000000)
     468        + (CodePoint >= 0x80000000) /* illegal */;
     469}
     470
     471
     472
    420473RT_C_DECLS_END
    421474/** @} */
  • trunk/src/VBox

  • trunk/src/VBox/Additions/WINNT/Graphics/Video/mp/wddm/VBoxMPVdma.cpp

    r51330 r51770  
    12631263NTSTATUS vboxVdmaTexPresentSetAlloc(PVBOXMP_DEVEXT pDevExt, const VBOXWDDM_ALLOC_DATA *pAllocData)
    12641264{
    1265     VBOXMP_CRPACKER CrPacker;
    1266     VBoxMpCrPackerInit(&CrPacker);
    12671265    uint32_t u32CrConClientID;
    1268 
    12691266    NTSTATUS Status = vboxVdmaCrCtlGetDefaultClientId(pDevExt, &u32CrConClientID);
    12701267    if (!NT_SUCCESS(Status))
     
    12731270        return Status;
    12741271    }
     1272
     1273    VBOXMP_CRPACKER *pCrPacker = (VBOXMP_CRPACKER *)RTMemTmpAlloc(sizeof(*pCrPacker));
     1274    if (!pCrPacker)
     1275        return STATUS_NO_MEMORY;
     1276    VBoxMpCrPackerInit(pCrPacker);
    12751277
    12761278    RECT Rect;
     
    12811283
    12821284    if (pDevExt->fCmdVbvaEnabled)
    1283         return vboxVdmaTexPresentSubmit(pDevExt, &CrPacker, u32CrConClientID, pAllocData->hostID, pAllocData->SurfDesc.VidPnSourceId, 0, 0, 1, (RTRECT*)&Rect);
    1284 
    1285     if (pDevExt->fTexPresentEnabled)
     1285        Status = vboxVdmaTexPresentSubmit(pDevExt, pCrPacker, u32CrConClientID, pAllocData->hostID, pAllocData->SurfDesc.VidPnSourceId, 0, 0, 1, (RTRECT*)&Rect);
     1286    else if (pDevExt->fTexPresentEnabled)
    12861287    {
    12871288        VBOXVDMAPIPE_RECTS RectInfo;
     
    12901291        RectInfo.UpdateRects.aRects[0] = Rect;
    12911292
    1292         return vboxVdmaProcessVRegTexPresent(pDevExt, &CrPacker, u32CrConClientID,
     1293        Status = vboxVdmaProcessVRegTexPresent(pDevExt, pCrPacker, u32CrConClientID,
    12931294                pAllocData, pAllocData,
    12941295                &Rect, &RectInfo);
    12951296    }
    1296 
    1297     return STATUS_NOT_IMPLEMENTED;
     1297    else
     1298        Status = STATUS_NOT_IMPLEMENTED;
     1299
     1300    RTMemTmpFree(pCrPacker);
     1301    return Status;
    12981302}
    12991303
  • trunk/src/VBox/Frontends

  • trunk/src/VBox/Frontends/VirtualBox/Makefile.kmk

    r51649 r51770  
    5757VirtualBoxHardened_NAME = VirtualBox
    5858VirtualBoxHardened_INST.darwin = $(INST_BIN)VirtualBox $(INST_BIN)VirtualBoxVM
     59VirtualBoxHardened_LDFLAGS.win = /SUBSYSTEM:$(if-expr "$(KBUILD_TYPE)" != "release",console,windows)
    5960
    6061
  • trunk/src/VBox/Frontends/VirtualBox/src/main.cpp

    r51679 r51770  
    638638    /* Prepare the error-message: */
    639639    QString strTitle = QApplication::tr("VirtualBox - Error In %1").arg(pszWhere);
    640     char msgBuf[1024];
    641     vsprintf(msgBuf, pszMsgFmt, va);
    642     QString strText = QApplication::tr("<html><b>%1 (rc=%2)</b><br/><br/>").arg(msgBuf).arg(rc);
     640
     641    char szMsgBuf[1024];
     642    RTStrPrintfV(szMsgBuf, sizeof(szMsgBuf), pszMsgFmt, va);
     643    QString strText = QApplication::tr("<html><b>%1 (rc=%2)</b><br/><br/>").arg(szMsgBuf).arg(rc);
     644
    643645    switch (enmWhat)
    644646    {
     
    652654# ifdef RT_OS_LINUX
    653655        case kSupInitOp_IPRT:
     656        case kSupInitOp_Misc:
    654657            if (rc == VERR_NO_MEMORY)
    655658                strText += g_QStrHintLinuxNoMemory;
     
    673676            break;
    674677    }
     678
    675679    strText += "</html>";
    676680
  • trunk/src/VBox/HostDrivers/Support/Makefile.kmk

    r51346 r51770  
    3131# Targets
    3232#
    33 LIBRARIES += SUPR3 SUPR3Static SUPR3HardenedStatic
     33LIBRARIES += SUPR3 SUPR3Static
     34ifdef VBOX_WITH_HARDENING
     35 LIBRARIES += SUPR3HardenedStatic
     36endif
     37DLLS.win += VBoxSupLib
    3438ifdef VBOX_WITH_32_ON_64_MAIN_API
    3539 LIBRARIES += SUPR3-x86
     
    7074endif # !VBOX_ONLY_DOCS && !VBOX_ONLY_EXTPACKS && !VBOX_ONLY_VALIDATIONKIT
    7175
     76#
     77# Authenticode related trust anchors and certificates -> .cpp
     78#
     79VBOX_SUP_WIN_CERTS_FILE = $(SUPR3_0_OUTDIR)/TrustAnchorsAndCerts.cpp
     80VBOX_SUP_WIN_CERTS := \
     81       SpcRootMicrosoft0=SpcRoot-MicrosoftAuthenticodeTmRootAuthority-01.taf \
     82       SpcRootMicrosoft1=SpcRoot-MicrosoftRootAuthority-00c1008b3c3c8811d13ef663ecdf40.taf \
     83       SpcRootMicrosoft2=SpcRoot-MicrosoftRootCertificateAuthority-79ad16a14aa0a5ad4c7358f407132e65.taf \
     84       SpcRootMicrosoft3=SpcRoot-MicrosoftRootCertificateAuthority2010-28cc3a25bfba44ac449a9b586b4339aa.taf \
     85       SpcRootMicrosoft4=SpcRoot-MicrosoftRootCertificateAuthority2011-3f8bc8b5fc9fb29643b569d66c42e144.taf \
     86       SpcRootMicrosoft5=SpcRoot-MicrosoftDigitalMediaAuthority2005-6eff330eb6e7569740680870104baaba.taf \
     87       NtRootMicrosoft6=NtRoot-MicrosoftCodeVerificationRoot-729404101f3e0ca347837fca175a8438.taf \
     88       TimeRootMicrosoft0=Timestamp-CopyrightC1997MicrosoftCorp-01.taf \
     89       TrustedCertVBox0=Trusted-OracleCorporationVirtualBox-51ca009816fdbd80f120e015ee75823e.taf
     90VBOX_SUP_WIN_CERT_NAMES := $(foreach cert,$(VBOX_SUP_WIN_CERTS),$(firstword $(subst =,$(SPACE) ,$(cert))))
     91VBOX_PATH_SUPR3_CERTIFICATES := $(PATH_SUB_CURRENT)/win/Certificates
     92
     93# 1=name, 2=filter, 3=buildcert?.
     94if "$(KBUILD_TARGET)" == "win" && defined(VBOX_WITH_HARDENING)
     95 VBOX_SUP_GEN_CERT_MACRO = 'SUPTAENTRY const g_aSUP$(1)TAs[] =' '{' \
     96       $(if-expr "$(3)" == "",,'    SUPTAENTRY_GEN(g_abSUPBuildCert),') \
     97        $(foreach certnm,$(filter $(2),$(VBOX_SUP_WIN_CERT_NAMES)), '    SUPTAENTRY_GEN(g_abSUP$(certnm)),') \
     98        '};' 'unsigned const g_cSUP$(1)TAs = RT_ELEMENTS(g_aSUP$(1)TAs);' '' ''
     99else
     100 VBOX_SUP_GEN_CERT_MACRO = 'SUPTAENTRY const g_aSUP$(1)TAs[] =' '{' \
     101        $(foreach certnm,$(filter $(2),$(VBOX_SUP_WIN_CERT_NAMES)), '    SUPTAENTRY_GEN(g_abSUP$(certnm)),') \
     102        '};' 'unsigned const g_cSUP$(1)TAs = RT_ELEMENTS(g_aSUP$(1)TAs);' '' ''
     103endif
     104
     105$$(VBOX_SUP_WIN_CERTS_FILE): $(MAKEFILE_CURRENT) \
     106                $(foreach cert,$(VBOX_SUP_WIN_CERTS),$(VBOX_PATH_SUPR3_CERTIFICATES)/$(lastword $(subst =,$(SPACE) ,$(cert)))) \
     107                $(VBOX_BIN2C) \
     108                $(if-expr  "$(KBUILD_TARGET)" == "win" && defined(VBOX_WITH_HARDENING),$(VBOX_RTSIGNTOOL)) \
     109                | $$(dir $$@)
     110        $(QUIET)$(RM) -f -- $@ [email protected]
     111        $(QUIET)$(APPEND) -n "$@" \
     112        '' \
     113        '#include <VBox/sup.h>' \
     114               ''
     115        $(foreach cert,$(VBOX_SUP_WIN_CERTS), $(NLTAB)$(VBOX_BIN2C) -ascii --append \
     116                "SUP$(firstword $(subst =,$(SP) ,$(cert)))" \
     117                "$(VBOX_PATH_SUPR3_CERTIFICATES)/$(lastword $(subst =,$(SP) ,$(cert)))" \
     118                "$@")
     119# The build certificate.
     120if "$(KBUILD_TARGET)" == "win" && defined(VBOX_WITH_HARDENING)
     121        $(VBOX_RTSIGNTOOL) extract-exe-signer-cert --exe $(VBOX_RTSIGNTOOL) --output "[email protected]" --der
     122        $(VBOX_BIN2C) -ascii --append SUPBuildCert "[email protected]" $@
     123        $(QUIET)$(RM) -f -- [email protected]
     124endif
     125# Generate certificate lists.
     126        $(QUIET)$(APPEND) -n "$@" '' \
     127               $(call VBOX_SUP_GEN_CERT_MACRO,All,%,build) \
     128               $(call VBOX_SUP_GEN_CERT_MACRO,SpcRoot,SpcRoot%) \
     129               $(call VBOX_SUP_GEN_CERT_MACRO,NtKernelRoot,NtRoot%) \
     130               $(call VBOX_SUP_GEN_CERT_MACRO,Timestamp,TimeRoot%) \
     131               $(call VBOX_SUP_GEN_CERT_MACRO,Trusted,TrustedCert%,build)
     132
     133tst: $(VBOX_SUP_WIN_CERTS_FILE)
     134
    72135
    73136#
    74137# The Ring-3 Support Library (this is linked into the IPRT dll, VBoxRT).
    75138#
    76 SUPR3_TEMPLATE     = VBOXR3NP
     139SUPR3_TEMPLATE      = VBOXR3NP
    77140SUPR3_DEFS          = \
    78141        IN_SUP_R3 IN_RT_R3 \
     
    88151        SUPR3HardenedIPRT.cpp \
    89152        SUPR3HardenedVerify.cpp \
    90         $(KBUILD_TARGET)/SUPLib-$(KBUILD_TARGET).cpp
     153        $(KBUILD_TARGET)/SUPLib-$(KBUILD_TARGET).cpp \
     154        $(VBOX_SUP_WIN_CERTS_FILE)
     155ifdef VBOX_WITH_HARDENING
     156 SUPR3_SOURCES.win  = \
     157        win/SUPHardenedVerifyImage-win.cpp
     158endif
    91159
    92160SUPR3-x86_TEMPLATE = VBoxR3Dll-x86
     
    95163
    96164#
    97 # Static version of SUPR3.
     165# Static version of SUPR3.  This is more of a stub than anything else in a
     166# hardened build, at least on windows.
    98167#
    99168SUPR3Static_TEMPLATE = VBOXR3STATIC
    100169SUPR3Static_EXTENDS = SUPR3
     170SUPR3Static_DEFS = $(SUPR3_DEFS) IN_SUP_R3_STATIC
     171SUPR3Static_SOURCES.win = $(filter-out win/SUPHardenedVerifyImage-win.cpp, $(SUPR3_SOURCES.win))
     172
    101173
    102174#
    103175# The static part of the hardened support library (ring-3).
    104176#
     177VBOX_PATH_RUNTIME_SRC ?= $(PATH_ROOT)/src/VBox/Runtime
    105178SUPR3HardenedStatic_TEMPLATE = VBOXR3HARDENEDLIB
    106179SUPR3HardenedStatic_DEFS     = IN_SUP_HARDENED_R3
     
    108181        $(if $(VBOX_WITH_SUPSVC),VBOX_WITH_SUPSVC,) \
    109182        $(if $(VBOX_WITH_MAIN),VBOX_WITH_MAIN,) \
    110         $(if $(VBOX_WITH_RAW_MODE),VBOX_WITH_RAW_MODE,)
     183        $(if $(VBOX_WITH_RAW_MODE),VBOX_WITH_RAW_MODE,) \
     184        $(if $(VBOX_WITHOUT_DEBUGGER_CHECKS),VBOX_WITHOUT_DEBUGGER_CHECKS,)
     185ifdef VBOX_WITH_VISTA_NO_SP
     186 SUPR3HardenedStatic_DEFS.win += VBOX_WITH_VISTA_NO_SP
     187endif
    111188SUPR3HardenedStatic_INCS     = .
    112189SUPR3HardenedStatic_SOURCES  = \
    113190        SUPR3HardenedMain.cpp \
    114191        SUPR3HardenedVerify.cpp \
     192        SUPR3HardenedNoCrt.cpp \
    115193        $(KBUILD_TARGET)/SUPLib-$(KBUILD_TARGET).cpp
     194SUPR3HardenedStatic_SOURCES.win = \
     195        win/SUPR3HardenedMain-win.cpp \
     196        win/SUPR3HardenedMainA-win.asm \
     197       win/SUPHardenedVerifyProcess-win.cpp \
     198       win/SUPHardenedVerifyImage-win.cpp \
     199        $(VBOX_SUP_WIN_CERTS_FILE)
     200
     201if1of ($(KBUILD_TARGET),win) ## @todo some of this move up.
     202 SUPR3HardenedStatic_SDKS += VBoxOpenSslHardened
     203 SUPR3HardenedStatic_DEFS += IN_RT IN_RT_R3 IN_RT_STATIC IPRT_NO_CRT RT_WITH_NOCRT_ALIASES LOG_DISABLED IPRT_NO_ERROR_DATA
     204 SUPR3HardenedStatic_DEFS.win += LDR_ONLY_PE __STRALIGN_H_
     205
     206 SUPR3HardenedStatic_INCS += $(PATH_ROOT)/include/iprt/nocrt  $(VBOX_PATH_RUNTIME_SRC)/include
     207
     208 SUPR3HardenedStatic_SOURCES += \
     209        $(VBOX_PATH_RUNTIME_SRC)/common/ldr/ldr.cpp \
     210        $(VBOX_PATH_RUNTIME_SRC)/common/ldr/ldrEx.cpp \
     211        $(VBOX_PATH_RUNTIME_SRC)/common/ldr/ldrPE.cpp \
     212        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-basics.cpp \
     213        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-cursor.cpp \
     214        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-default-allocator.cpp \
     215        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-dump.cpp \
     216        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-encode.cpp \
     217        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-bitstring.cpp \
     218        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-bitstring-decode.cpp \
     219        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-boolean.cpp \
     220        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-boolean-decode.cpp \
     221        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-core.cpp \
     222        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-core-decode.cpp \
     223        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-dyntype.cpp \
     224        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-dyntype-decode.cpp \
     225        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-integer.cpp \
     226        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-integer-decode.cpp \
     227        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-null.cpp \
     228        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-null-decode.cpp \
     229        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-objid.cpp \
     230        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-objid-decode.cpp \
     231        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-octetstring.cpp \
     232        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-octetstring-decode.cpp \
     233        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-string.cpp \
     234        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-string-decode.cpp \
     235        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-time.cpp \
     236        $(VBOX_PATH_RUNTIME_SRC)/common/asn1/asn1-ut-time-decode.cpp \
     237        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/digest-core.cpp \
     238        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/digest-builtin.cpp \
     239        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkcs7-asn1-decoder.cpp \
     240        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkcs7-core.cpp \
     241        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkcs7-init.cpp \
     242        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkcs7-sanity.cpp \
     243        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkcs7-verify.cpp \
     244        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkix-signature-builtin.cpp \
     245        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkix-signature-core.cpp \
     246        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkix-signature-rsa.cpp \
     247        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkix-verify.cpp \
     248        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/pkix-util.cpp \
     249        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/rsa-asn1-decoder.cpp \
     250        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/rsa-core.cpp \
     251        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/rsa-init.cpp \
     252        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/rsa-sanity.cpp \
     253        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/spc-asn1-decoder.cpp \
     254        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/spc-core.cpp \
     255        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/spc-init.cpp \
     256        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/spc-sanity.cpp \
     257        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/x509-asn1-decoder.cpp \
     258        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/x509-certpaths.cpp \
     259        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/x509-core.cpp \
     260        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/x509-init.cpp \
     261        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/x509-sanity.cpp \
     262        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/x509-verify.cpp \
     263        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/store.cpp \
     264        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/store-inmem.cpp \
     265        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/taf-asn1-decoder.cpp \
     266        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/taf-core.cpp \
     267        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/taf-init.cpp \
     268        $(VBOX_PATH_RUNTIME_SRC)/common/crypto/taf-sanity.cpp \
     269        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/md2.cpp \
     270        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/md5.cpp \
     271        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/sha1.cpp \
     272        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/sha256.cpp \
     273        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/sha512.cpp \
     274        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/md2str.cpp \
     275        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/md5str.cpp \
     276        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/sha1str.cpp \
     277        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/sha256str.cpp \
     278        $(VBOX_PATH_RUNTIME_SRC)/common/checksum/sha512str.cpp \
     279        $(VBOX_PATH_RUNTIME_SRC)/common/err/errinfo.cpp \
     280        $(VBOX_PATH_RUNTIME_SRC)/common/path/RTPathChangeToUnixSlashes.cpp \
     281        $(VBOX_PATH_RUNTIME_SRC)/common/path/RTPathExt.cpp \
     282        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTStrPrintHexBytes.cpp \
     283        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTUtf16PrintHexBytes.cpp \
     284        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTUtf16ICmpAscii.cpp \
     285        $(VBOX_PATH_RUNTIME_SRC)/common/string/strstrip.cpp \
     286       \
     287        $(VBOX_PATH_RUNTIME_SRC)/common/err/errmsg.cpp \
     288        $(VBOX_PATH_RUNTIME_SRC)/common/math/bignum.cpp \
     289        $(VBOX_PATH_RUNTIME_SRC)/common/misc/RTAssertMsg1Weak.cpp \
     290        $(VBOX_PATH_RUNTIME_SRC)/common/misc/RTAssertMsg2Weak.cpp \
     291        $(VBOX_PATH_RUNTIME_SRC)/common/misc/RTAssertMsg2WeakV.cpp \
     292        $(VBOX_PATH_RUNTIME_SRC)/common/string/memchr.asm \
     293        $(VBOX_PATH_RUNTIME_SRC)/common/string/memcmp.asm \
     294        $(VBOX_PATH_RUNTIME_SRC)/common/string/memcpy.asm \
     295        $(VBOX_PATH_RUNTIME_SRC)/common/string/memmove.asm \
     296        $(VBOX_PATH_RUNTIME_SRC)/common/string/mempcpy.asm \
     297        $(VBOX_PATH_RUNTIME_SRC)/common/string/memset.asm \
     298        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTStrCat.cpp \
     299        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTStrCmp.cpp \
     300        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTStrCopy.cpp \
     301        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTStrNCmp.cpp \
     302        $(VBOX_PATH_RUNTIME_SRC)/common/string/RTStrNLen.cpp \
     303        $(VBOX_PATH_RUNTIME_SRC)/common/string/strchr.asm \
     304        $(VBOX_PATH_RUNTIME_SRC)/common/string/strcmp.asm \
     305        $(VBOX_PATH_RUNTIME_SRC)/common/string/strcpy.asm \
     306        $(VBOX_PATH_RUNTIME_SRC)/common/string/strformat.cpp \
     307        $(VBOX_PATH_RUNTIME_SRC)/common/string/strformatrt.cpp \
     308        $(VBOX_PATH_RUNTIME_SRC)/common/string/strformattype.cpp \
     309        $(VBOX_PATH_RUNTIME_SRC)/common/string/stringalloc.cpp \
     310        $(VBOX_PATH_RUNTIME_SRC)/common/string/strlen.asm \
     311        $(VBOX_PATH_RUNTIME_SRC)/common/string/strncmp.asm \
     312        $(VBOX_PATH_RUNTIME_SRC)/common/string/strncpy.asm \
     313        $(VBOX_PATH_RUNTIME_SRC)/common/string/strprintf.cpp \
     314        $(VBOX_PATH_RUNTIME_SRC)/common/string/strtonum.cpp \
     315        $(VBOX_PATH_RUNTIME_SRC)/common/string/utf-16.cpp \
     316        $(VBOX_PATH_RUNTIME_SRC)/common/string/utf-8.cpp \
     317        $(VBOX_PATH_RUNTIME_SRC)/common/string/utf-8-case.cpp \
     318        $(VBOX_PATH_RUNTIME_SRC)/common/string/unidata-upper.cpp \
     319        $(VBOX_PATH_RUNTIME_SRC)/common/string/unidata-lower.cpp \
     320        $(VBOX_PATH_RUNTIME_SRC)/common/time/time.cpp \
     321        $(VBOX_PATH_RUNTIME_SRC)/generic/RTAssertShouldPanic-generic.cpp \
     322        $(VBOX_PATH_RUNTIME_SRC)/generic/memsafer-generic.cpp \
     323        $(VBOX_PATH_RUNTIME_SRC)/generic/uuid-generic.cpp \
     324
     325
     326 SUPR3HardenedStatic_SOURCES.win += \
     327        win/SUPR3HardenedNoCrt-win.cpp \
     328        $(VBOX_PATH_RUNTIME_SRC)/nt/RTErrConvertFromNtStatus.cpp \
     329        $(VBOX_PATH_RUNTIME_SRC)/win/RTErrConvertFromWin32.cpp \
     330        $(VBOX_PATH_RUNTIME_SRC)/win/errmsgwin.cpp
     331
     332 # Add necessary compiler specific files from libcmt.lib and the lib dir.
     333 ifeq ($(KBUILD_TARGET),win)
     334   SUPR3HardenedStatic_VBOX_LIBC_OBJS = chkstk.obj
     335   ifeq ($(KBUILD_TARGET_ARCH),x86)
     336    SUPR3HardenedStatic_VBOX_LIBC_OBJS += alloca16.obj
     337   endif
     338  SUPR3HardenedStatic_SOURCES.win += $(addprefix $(SUPR3HardenedStatic_0_OUTDIR)/,$(SUPR3HardenedStatic_VBOX_LIBC_OBJS))
     339
     340  $(addprefix $$(SUPR3HardenedStatic_0_OUTDIR)/,$(SUPR3HardenedStatic_VBOX_LIBC_OBJS)): \
     341                $$(PATH_TOOL_$(TEMPLATE_VBOXR3EXE_TOOL.win.$(KBUILD_TARGET_ARCH))_LIB)/libcmt.lib | $$(dir $$@)
     342        $(TOOL_$(TEMPLATE_VBOXR3HARDENEDEXE_TOOL.win.$(KBUILD_TARGET_ARCH))_AR) "$<" \
     343                /EXTRACT:`$(TOOL_$(TEMPLATE_VBOXR3HARDENEDEXE_TOOL.win.$(KBUILD_TARGET_ARCH))_AR) "$<" /LIST \
     344                          | $(SED_EXT) -n -e '/$(notdir $@)/p'` \
     345                "/OUT:$@"
     346 endif
     347endif
     348
     349
     350#
     351# VBoxSupLib - Windows DLL for catching thread creation and termination.
     352#
     353VBoxSupLib_TEMPLATE = $(if "$(KBUILD_TARGET)" == "win",VBOXR3HARDENEDLIB,VBOXR3)
     354VBoxSupLib_LDFLAGS.win.amd64 = -Entry:DllMainEntrypoint
     355VBoxSupLib_LDFLAGS.win.x86   = -Entry:DllMainEntrypoint
     356VBoxSupLib_DEFS = \
     357        $(if $(VBOX_WITHOUT_DEBUGGER_CHECKS),VBOX_WITHOUT_DEBUGGER_CHECKS,)
     358VBoxSupLib_SOURCES = \
     359        $(KBUILD_TARGET)/VBoxSupLib-$(KBUILD_TARGET).cpp
     360VBoxSupLib_LIBS.win = \
     361        $(SUPR3HardenedStatic_1_INS_TARGET)
     362
    116363
    117364#
     
    263510 VBoxDrv_DEBUG_INST.darwin= $(patsubst %/,%,$(INST_VBOXDRV))
    264511 VBoxDrv_SDKS.win         = ReorderCompilerIncs $(VBOX_WINDDK) $(VBOX_WINPSDK)INCS
     512 ifdef VBOX_WITH_HARDENING
     513  VBoxDrv_SDKS.win       += VBoxOpenSslHardened
     514 endif
    265515
    266516 VBoxDrv_DEFS            := IN_RT_R0 IN_SUP_R0 SUPDRV_WITH_RELEASE_LOGGER VBOX_SVN_REV=$(VBOX_SVN_REV)
    267517 ifdef VBOX_WITH_DTRACE_R0DRV
    268518  VBoxDrv_DEFS           += VBOX_WITH_DTRACE VBOX_WITH_DTRACE_R0DRV
     519 endif
     520 ifdef VBOX_WITHOUT_DEBUGGER_CHECKS
     521  VBoxDrv_DEFS           += VBOX_WITHOUT_DEBUGGER_CHECKS
    269522 endif
    270523 #VBoxDrv_DEFS.debug      += DEBUG_DARWIN_GIP
     
    284537  VBoxDrv_DEFS.win       += VBOX_WITHOUT_NATIVE_R0_LOADER
    285538 endif
     539 ifdef VBOX_WITH_VISTA_NO_SP
     540  VBoxDrv_DEFS.win       += VBOX_WITH_VISTA_NO_SP
     541 endif
    286542
    287543 VBoxDrv_INCS             = . $(VBoxDrv_0_OUTDIR)
     
    292548 VBoxDrv_LIBS.linux.debug = $(VBoxDrv_LIBS) $(VBOX_GCC_LIBGCC)
    293549 VBoxDrv_LIBS.win         = \
     550        $(PATH_STAGE_LIB)/RuntimeR0Drv$(VBOX_SUFF_LIB) \
    294551        $(PATH_SDK_$(VBOX_WINDDK)_LIB)/ntoskrnl.lib \
    295         $(PATH_SDK_$(VBOX_WINDDK)_LIB)/hal.lib \
    296         $(PATH_STAGE_LIB)/RuntimeR0Drv$(VBOX_SUFF_LIB)
     552        $(PATH_SDK_$(VBOX_WINDDK)_LIB)/hal.lib
    297553
    298554 #VBoxDrv_LDFLAGS.darwin    = -v -Wl,-whyload -Wl,-v -Wl,-whatsloaded
     
    314570        win/SUPDrvA-win.asm \
    315571        win/VBoxDrv.rc
     572 ifdef VBOX_WITH_HARDENING
     573  VBoxDrv_SOURCES.win    += \
     574        win/SUPHardenedVerifyImage-win.cpp \
     575        win/SUPHardenedVerifyProcess-win.cpp \
     576        $(VBOX_SUP_WIN_CERTS_FILE)
     577 endif
    316578 VBoxDrv_SOURCES          = \
    317579        SUPDrv.d \
  • trunk/src/VBox/HostDrivers/Support/SUPDrv.c

    r51718 r51770  
    464464     * Initialize it.
    465465     */
    466     memset(pDevExt, 0, sizeof(*pDevExt));
     466    memset(pDevExt, 0, sizeof(*pDevExt)); /* Does not wipe OS specific tail section of the structure. */
     467    pDevExt->Spinlock = NIL_RTSPINLOCK;
     468    pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
     469    pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
    467470    rc = RTSpinlockCreate(&pDevExt->Spinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvDevExt");
    468471    if (RT_SUCCESS(rc))
    469     {
    470472        rc = RTSpinlockCreate(&pDevExt->hGipSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvGip");
     473    if (RT_SUCCESS(rc))
     474        rc = RTSpinlockCreate(&pDevExt->hSessionHashTabSpinlock, RTSPINLOCK_FLAGS_INTERRUPT_SAFE, "SUPDrvSession");
     475
     476    if (RT_SUCCESS(rc))
     477#ifdef SUPDRV_USE_MUTEX_FOR_LDR
     478        rc = RTSemMutexCreate(&pDevExt->mtxLdr);
     479#else
     480        rc = RTSemFastMutexCreate(&pDevExt->mtxLdr);
     481#endif
     482    if (RT_SUCCESS(rc))
     483    {
     484        rc = RTSemFastMutexCreate(&pDevExt->mtxComponentFactory);
    471485        if (RT_SUCCESS(rc))
    472486        {
    473487#ifdef SUPDRV_USE_MUTEX_FOR_LDR
    474             rc = RTSemMutexCreate(&pDevExt->mtxLdr);
     488            rc = RTSemMutexCreate(&pDevExt->mtxGip);
    475489#else
    476             rc = RTSemFastMutexCreate(&pDevExt->mtxLdr);
     490            rc = RTSemFastMutexCreate(&pDevExt->mtxGip);
    477491#endif
    478492            if (RT_SUCCESS(rc))
    479493            {
    480                 rc = RTSemFastMutexCreate(&pDevExt->mtxComponentFactory);
     494                rc = supdrvGipCreate(pDevExt);
    481495                if (RT_SUCCESS(rc))
    482496                {
    483 #ifdef SUPDRV_USE_MUTEX_FOR_LDR
    484                     rc = RTSemMutexCreate(&pDevExt->mtxGip);
    485 #else
    486                     rc = RTSemFastMutexCreate(&pDevExt->mtxGip);
    487 #endif
     497                    rc = supdrvTracerInit(pDevExt);
    488498                    if (RT_SUCCESS(rc))
    489499                    {
    490                         rc = supdrvGipCreate(pDevExt);
    491                         if (RT_SUCCESS(rc))
    492                         {
    493                             rc = supdrvTracerInit(pDevExt);
    494                             if (RT_SUCCESS(rc))
    495                             {
    496                                 pDevExt->pLdrInitImage  = NULL;
    497                                 pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
    498                                 pDevExt->u32Cookie      = BIRD;  /** @todo make this random? */
    499                                 pDevExt->cbSession      = (uint32_t)cbSession;
    500 
    501                                 /*
    502                                  * Fixup the absolute symbols.
    503                                  *
    504                                  * Because of the table indexing assumptions we'll have a little #ifdef orgy
    505                                  * here rather than distributing this to OS specific files. At least for now.
    506                                  */
     500                        pDevExt->pLdrInitImage  = NULL;
     501                        pDevExt->hLdrInitThread = NIL_RTNATIVETHREAD;
     502                        pDevExt->u32Cookie      = BIRD;  /** @todo make this random? */
     503                        pDevExt->cbSession      = (uint32_t)cbSession;
     504
     505                        /*
     506                         * Fixup the absolute symbols.
     507                         *
     508                         * Because of the table indexing assumptions we'll have a little #ifdef orgy
     509                         * here rather than distributing this to OS specific files. At least for now.
     510                         */
    507511#ifdef RT_OS_DARWIN
    508512# if ARCH_BITS == 32
    509                                 if (SUPR0GetPagingMode() >= SUPPAGINGMODE_AMD64)
    510                                 {
    511                                     g_aFunctions[0].pfn = (void *)1;                    /* SUPR0AbsIs64bit */
    512                                     g_aFunctions[1].pfn = (void *)0x80;                 /* SUPR0Abs64bitKernelCS - KERNEL64_CS, seg.h */
    513                                     g_aFunctions[2].pfn = (void *)0x88;                 /* SUPR0Abs64bitKernelSS - KERNEL64_SS, seg.h */
    514                                     g_aFunctions[3].pfn = (void *)0x88;                 /* SUPR0Abs64bitKernelDS - KERNEL64_SS, seg.h */
    515                                 }
    516                                 else
    517                                     g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[4].pfn = (void *)0;
    518                                 g_aFunctions[4].pfn = (void *)0x08;                     /* SUPR0AbsKernelCS - KERNEL_CS, seg.h */
    519                                 g_aFunctions[5].pfn = (void *)0x10;                     /* SUPR0AbsKernelSS - KERNEL_DS, seg.h */
    520                                 g_aFunctions[6].pfn = (void *)0x10;                     /* SUPR0AbsKernelDS - KERNEL_DS, seg.h */
    521                                 g_aFunctions[7].pfn = (void *)0x10;                     /* SUPR0AbsKernelES - KERNEL_DS, seg.h */
    522                                 g_aFunctions[8].pfn = (void *)0x10;                     /* SUPR0AbsKernelFS - KERNEL_DS, seg.h */
    523                                 g_aFunctions[9].pfn = (void *)0x48;                     /* SUPR0AbsKernelGS - CPU_DATA_GS, seg.h */
     513                        if (SUPR0GetPagingMode() >= SUPPAGINGMODE_AMD64)
     514                        {
     515                            g_aFunctions[0].pfn = (void *)1;                    /* SUPR0AbsIs64bit */
     516                            g_aFunctions[1].pfn = (void *)0x80;                 /* SUPR0Abs64bitKernelCS - KERNEL64_CS, seg.h */
     517                            g_aFunctions[2].pfn = (void *)0x88;                 /* SUPR0Abs64bitKernelSS - KERNEL64_SS, seg.h */
     518                            g_aFunctions[3].pfn = (void *)0x88;                 /* SUPR0Abs64bitKernelDS - KERNEL64_SS, seg.h */
     519                        }
     520                        else
     521                            g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[4].pfn = (void *)0;
     522                        g_aFunctions[4].pfn = (void *)0x08;                     /* SUPR0AbsKernelCS - KERNEL_CS, seg.h */
     523                        g_aFunctions[5].pfn = (void *)0x10;                     /* SUPR0AbsKernelSS - KERNEL_DS, seg.h */
     524                        g_aFunctions[6].pfn = (void *)0x10;                     /* SUPR0AbsKernelDS - KERNEL_DS, seg.h */
     525                        g_aFunctions[7].pfn = (void *)0x10;                     /* SUPR0AbsKernelES - KERNEL_DS, seg.h */
     526                        g_aFunctions[8].pfn = (void *)0x10;                     /* SUPR0AbsKernelFS - KERNEL_DS, seg.h */
     527                        g_aFunctions[9].pfn = (void *)0x48;                     /* SUPR0AbsKernelGS - CPU_DATA_GS, seg.h */
    524528# else /* 64-bit darwin: */
    525                                 g_aFunctions[0].pfn = (void *)1;                        /* SUPR0AbsIs64bit */
    526                                 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0Abs64bitKernelCS */
    527                                 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0Abs64bitKernelSS */
    528                                 g_aFunctions[3].pfn = (void *)0;                        /* SUPR0Abs64bitKernelDS */
    529                                 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0AbsKernelCS */
    530                                 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0AbsKernelSS */
    531                                 g_aFunctions[6].pfn = (void *)0;                        /* SUPR0AbsKernelDS */
    532                                 g_aFunctions[7].pfn = (void *)0;                        /* SUPR0AbsKernelES */
    533                                 g_aFunctions[8].pfn = (void *)0;                        /* SUPR0AbsKernelFS */
    534                                 g_aFunctions[9].pfn = (void *)0;                        /* SUPR0AbsKernelGS */
     529                        g_aFunctions[0].pfn = (void *)1;                        /* SUPR0AbsIs64bit */
     530                        g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0Abs64bitKernelCS */
     531                        g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0Abs64bitKernelSS */
     532                        g_aFunctions[3].pfn = (void *)0;                        /* SUPR0Abs64bitKernelDS */
     533                        g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0AbsKernelCS */
     534                        g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0AbsKernelSS */
     535                        g_aFunctions[6].pfn = (void *)0;                        /* SUPR0AbsKernelDS */
     536                        g_aFunctions[7].pfn = (void *)0;                        /* SUPR0AbsKernelES */
     537                        g_aFunctions[8].pfn = (void *)0;                        /* SUPR0AbsKernelFS */
     538                        g_aFunctions[9].pfn = (void *)0;                        /* SUPR0AbsKernelGS */
    535539
    536540# endif
    537541#else  /* !RT_OS_DARWIN */
    538542# if ARCH_BITS == 64
    539                                 g_aFunctions[0].pfn = (void *)1;                        /* SUPR0AbsIs64bit */
    540                                 g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0Abs64bitKernelCS */
    541                                 g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0Abs64bitKernelSS */
    542                                 g_aFunctions[3].pfn = (void *)(uintptr_t)ASMGetDS();    /* SUPR0Abs64bitKernelDS */
     543                        g_aFunctions[0].pfn = (void *)1;                        /* SUPR0AbsIs64bit */
     544                        g_aFunctions[1].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0Abs64bitKernelCS */
     545                        g_aFunctions[2].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0Abs64bitKernelSS */
     546                        g_aFunctions[3].pfn = (void *)(uintptr_t)ASMGetDS();    /* SUPR0Abs64bitKernelDS */
    543547# else
    544                                 g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[4].pfn = (void *)0;
     548                        g_aFunctions[0].pfn = g_aFunctions[1].pfn = g_aFunctions[2].pfn = g_aFunctions[4].pfn = (void *)0;
    545549# endif
    546                                 g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0AbsKernelCS */
    547                                 g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0AbsKernelSS */
    548                                 g_aFunctions[6].pfn = (void *)(uintptr_t)ASMGetDS();    /* SUPR0AbsKernelDS */
    549                                 g_aFunctions[7].pfn = (void *)(uintptr_t)ASMGetES();    /* SUPR0AbsKernelES */
    550                                 g_aFunctions[8].pfn = (void *)(uintptr_t)ASMGetFS();    /* SUPR0AbsKernelFS */
    551                                 g_aFunctions[9].pfn = (void *)(uintptr_t)ASMGetGS();    /* SUPR0AbsKernelGS */
     550                        g_aFunctions[4].pfn = (void *)(uintptr_t)ASMGetCS();    /* SUPR0AbsKernelCS */
     551                        g_aFunctions[5].pfn = (void *)(uintptr_t)ASMGetSS();    /* SUPR0AbsKernelSS */
     552                        g_aFunctions[6].pfn = (void *)(uintptr_t)ASMGetDS();    /* SUPR0AbsKernelDS */
     553                        g_aFunctions[7].pfn = (void *)(uintptr_t)ASMGetES();    /* SUPR0AbsKernelES */
     554                        g_aFunctions[8].pfn = (void *)(uintptr_t)ASMGetFS();    /* SUPR0AbsKernelFS */
     555                        g_aFunctions[9].pfn = (void *)(uintptr_t)ASMGetGS();    /* SUPR0AbsKernelGS */
    552556#endif /* !RT_OS_DARWIN */
    553                                 return VINF_SUCCESS;
    554                             }
    555 
    556                             supdrvGipDestroy(pDevExt);
    557                         }
     557                        return VINF_SUCCESS;
     558                    }
     559
     560                    supdrvGipDestroy(pDevExt);
     561                }
    558562
    559563#ifdef SUPDRV_USE_MUTEX_FOR_GIP
    560                         RTSemMutexDestroy(pDevExt->mtxGip);
    561                         pDevExt->mtxGip = NIL_RTSEMMUTEX;
     564                RTSemMutexDestroy(pDevExt->mtxGip);
     565                pDevExt->mtxGip = NIL_RTSEMMUTEX;
    562566#else
    563                         RTSemFastMutexDestroy(pDevExt->mtxGip);
    564                         pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
    565 #endif
    566                     }
    567                     RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
    568                     pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
    569                 }
    570 #ifdef SUPDRV_USE_MUTEX_FOR_LDR
    571                 RTSemMutexDestroy(pDevExt->mtxLdr);
    572                 pDevExt->mtxLdr = NIL_RTSEMMUTEX;
    573 #else
    574                 RTSemFastMutexDestroy(pDevExt->mtxLdr);
    575                 pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
     567                RTSemFastMutexDestroy(pDevExt->mtxGip);
     568                pDevExt->mtxGip = NIL_RTSEMFASTMUTEX;
    576569#endif
    577570            }
    578             RTSpinlockDestroy(pDevExt->hGipSpinlock);
    579             pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
    580         }
    581         RTSpinlockDestroy(pDevExt->Spinlock);
    582         pDevExt->Spinlock = NIL_RTSPINLOCK;
    583     }
     571            RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
     572            pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
     573        }
     574#ifdef SUPDRV_USE_MUTEX_FOR_LDR
     575        RTSemMutexDestroy(pDevExt->mtxLdr);
     576        pDevExt->mtxLdr = NIL_RTSEMMUTEX;
     577#else
     578        RTSemFastMutexDestroy(pDevExt->mtxLdr);
     579        pDevExt->mtxLdr = NIL_RTSEMFASTMUTEX;
     580#endif
     581    }
     582
     583    RTSpinlockDestroy(pDevExt->Spinlock);
     584    pDevExt->Spinlock = NIL_RTSPINLOCK;
     585    RTSpinlockDestroy(pDevExt->hGipSpinlock);
     586    pDevExt->hGipSpinlock = NIL_RTSPINLOCK;
     587    RTSpinlockDestroy(pDevExt->hSessionHashTabSpinlock);
     588    pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
     589
    584590#ifdef SUPDRV_WITH_RELEASE_LOGGER
    585591    RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
     
    622628    RTSemFastMutexDestroy(pDevExt->mtxComponentFactory);
    623629    pDevExt->mtxComponentFactory = NIL_RTSEMFASTMUTEX;
     630    RTSpinlockDestroy(pDevExt->hSessionHashTabSpinlock);
     631    pDevExt->hSessionHashTabSpinlock = NIL_RTSPINLOCK;
    624632
    625633    /*
     
    700708                pSession->u32Cookie         = BIRD_INV;
    701709                pSession->fUnrestricted     = fUnrestricted;
     710                /*pSession->fInHashTable      = false; */
    702711                pSession->cRefs             = 1;
    703                 /*pSession->pLdrUsage         = NULL;
    704                 pSession->pVM               = NULL;
    705                 pSession->pUsage            = NULL;
    706                 pSession->pGip              = NULL;
    707                 pSession->fGipReferenced    = false;
    708                 pSession->Bundle.cUsed      = 0; */
    709                 pSession->Uid               = NIL_RTUID;
    710                 pSession->Gid               = NIL_RTGID;
     712                /*pSession->pCommonNextHash   = NULL;
     713                pSession->ppOsSessionPtr    = NULL; */
    711714                if (fUser)
    712715                {
     
    719722                    pSession->R0Process     = NIL_RTR0PROCESS;
    720723                }
     724                /*pSession->pLdrUsage         = NULL;
     725                pSession->pVM               = NULL;
     726                pSession->pUsage            = NULL;
     727                pSession->pGip              = NULL;
     728                pSession->fGipReferenced    = false;
     729                pSession->Bundle.cUsed      = 0; */
     730                pSession->Uid               = NIL_RTUID;
     731                pSession->Gid               = NIL_RTGID;
    721732                /*pSession->uTracerData       = 0;*/
    722733                pSession->hTracerCaller     = NIL_RTNATIVETHREAD;
     
    746757
    747758/**
    748  * Shared code for cleaning up a session (but not quite freeing it).
    749  *
    750  * This is primarily intended for MAC OS X where we have to clean up the memory
    751  * stuff before the file handle is closed.
    752  *
    753  * @param   pDevExt     Device extension.
     759 * Cleans up the session in the context of the process to which it belongs, the
     760 * caller will free the session and the session spinlock.
     761 *
     762 * This should normally occur when the session is closed or as the process
     763 * exits.  Careful reference counting in the OS specfic code makes sure that
     764 * there cannot be any races between process/handle cleanup callbacks and
     765 * threads doing I/O control calls.
     766 *
     767 * @param   pDevExt     The device extension.
    754768 * @param   pSession    Session data.
    755  *                      This data will be freed by this routine.
    756769 */
    757770static void supdrvCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     
    760773    PSUPDRVBUNDLE       pBundle;
    761774    LogFlow(("supdrvCleanupSession: pSession=%p\n", pSession));
     775
     776    Assert(!pSession->fInHashTable);
     777    Assert(!pSession->ppOsSessionPtr);
     778    AssertReleaseMsg(pSession->R0Process == RTR0ProcHandleSelf() || pSession->R0Process == NIL_RTR0PROCESS,
     779                     ("R0Process=%p cur=%p; Process=%u curpid=%u\n", RTR0ProcHandleSelf(), RTProcSelf()));
    762780
    763781    /*
     
    964982
    965983/**
    966  * Shared code for cleaning up a session.
     984 * Common code for freeing a session when the reference count reaches zero.
    967985 *
    968986 * @param   pDevExt     Device extension.
     
    970988 *                      This data will be freed by this routine.
    971989 */
    972 static void supdrvCloseSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     990static void supdrvDestroySession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
    973991{
    974992    VBOXDRV_SESSION_CLOSE(pSession);
     
    978996     */
    979997    supdrvCleanupSession(pDevExt, pSession);
     998    supdrvOSCleanupSession(pDevExt, pSession);
    980999
    9811000    /*
     
    9861005    pSession->pDevExt = NULL;
    9871006    RTMemFree(pSession);
    988     LogFlow(("supdrvCloseSession: returns\n"));
     1007    LogFlow(("supdrvDestroySession: returns\n"));
     1008}
     1009
     1010
     1011/**
     1012 * Inserts the session into the global hash table.
     1013 *
     1014 * @retval  VINF_SUCCESS on success.
     1015 * @retval  VERR_WRONG_ORDER if the session was already inserted (asserted).
     1016 * @retval  VERR_INVALID_PARAMETER if the session handle is invalid or a ring-0
     1017 *          session (asserted).
     1018 * @retval  VERR_DUPLICATE if there is already a session for that pid.
     1019 *
     1020 * @param   pDevExt         The device extension.
     1021 * @param   pSession        The session.
     1022 * @param   ppOsSessionPtr  Pointer to the OS session pointer, if any is
     1023 *                          available and used.  This will set to point to the
     1024 *                          session while under the protection of the session
     1025 *                          hash table spinlock.  It will also be kept in
     1026 *                          PSUPDRVSESSION::ppOsSessionPtr for lookup and
     1027 *                          cleanup use.
     1028 * @param   pvUser          Argument for supdrvOSSessionHashTabInserted.
     1029 */
     1030int VBOXCALL supdrvSessionHashTabInsert(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVSESSION *ppOsSessionPtr,
     1031                                        void *pvUser)
     1032{
     1033    PSUPDRVSESSION  pCur;
     1034    unsigned        iHash;
     1035
     1036    /*
     1037     * Validate input.
     1038     */
     1039    AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
     1040    AssertReturn(pSession->R0Process != NIL_RTR0PROCESS, VERR_INVALID_PARAMETER);
     1041
     1042    /*
     1043     * Calculate the hash table index and acquire the spinlock.
     1044     */
     1045    iHash = SUPDRV_SESSION_HASH(pSession->Process);
     1046
     1047    RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
     1048
     1049    /*
     1050     * If there are a collisions, we need to carefully check if we got a
     1051     * duplicate.  There can only be one open session per process.
     1052     */
     1053    pCur = pDevExt->apSessionHashTab[iHash];
     1054    if (pCur)
     1055    {
     1056        while (pCur && pCur->Process != pSession->Process)
     1057            pCur = pCur->pCommonNextHash;
     1058
     1059        if (pCur)
     1060        {
     1061            RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
     1062            if (pCur == pSession)
     1063            {
     1064                Assert(pSession->fInHashTable);
     1065                AssertFailed();
     1066                return VERR_WRONG_ORDER;
     1067            }
     1068            Assert(!pSession->fInHashTable);
     1069            if (pCur->R0Process == pSession->R0Process)
     1070                return VERR_RESOURCE_IN_USE;
     1071            return VERR_DUPLICATE;
     1072        }
     1073    }
     1074    Assert(!pSession->fInHashTable);
     1075    Assert(!pSession->ppOsSessionPtr);
     1076
     1077    /*
     1078     * Insert it, doing a callout to the OS specific code in case it has
     1079     * anything it wishes to do while we're holding the spinlock.
     1080     */
     1081    pSession->pCommonNextHash = pDevExt->apSessionHashTab[iHash];
     1082    pDevExt->apSessionHashTab[iHash] = pSession;
     1083    pSession->fInHashTable    = true;
     1084    ASMAtomicIncS32(&pDevExt->cSessions);
     1085
     1086    pSession->ppOsSessionPtr = ppOsSessionPtr;
     1087    if (ppOsSessionPtr)
     1088        ASMAtomicWritePtr(ppOsSessionPtr, pSession);
     1089
     1090    supdrvOSSessionHashTabInserted(pDevExt, pSession, pvUser);
     1091
     1092    /*
     1093     * Retain a reference for the pointer in the session table.
     1094     */
     1095    ASMAtomicIncU32(&pSession->cRefs);
     1096
     1097    RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
     1098    return VINF_SUCCESS;
     1099}
     1100
     1101
     1102/**
     1103 * Removes the session from the global hash table.
     1104 *
     1105 * @retval  VINF_SUCCESS on success.
     1106 * @retval  VERR_NOT_FOUND if the session was already removed (asserted).
     1107 * @retval  VERR_INVALID_PARAMETER if the session handle is invalid or a ring-0
     1108 *          session (asserted).
     1109 *
     1110 * @param   pDevExt     The device extension.
     1111 * @param   pSession    The session. The caller is expected to have a reference
     1112 *                      to this so it won't croak on us when we release the hash
     1113 *                      table reference.
     1114 * @param   pvUser      OS specific context value for the
     1115 *                      supdrvOSSessionHashTabInserted callback.
     1116 */
     1117int VBOXCALL supdrvSessionHashTabRemove(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     1118{
     1119    PSUPDRVSESSION  pCur;
     1120    unsigned        iHash;
     1121    int32_t         cRefs;
     1122
     1123    /*
     1124     * Validate input.
     1125     */
     1126    AssertReturn(SUP_IS_SESSION_VALID(pSession), VERR_INVALID_PARAMETER);
     1127    AssertReturn(pSession->R0Process != NIL_RTR0PROCESS, VERR_INVALID_PARAMETER);
     1128
     1129    /*
     1130     * Calculate the hash table index and acquire the spinlock.
     1131     */
     1132    iHash = SUPDRV_SESSION_HASH(pSession->Process);
     1133
     1134    RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
     1135
     1136    /*
     1137     * Unlink it.
     1138     */
     1139    pCur = pDevExt->apSessionHashTab[iHash];
     1140    if (pCur == pSession)
     1141        pDevExt->apSessionHashTab[iHash] = pSession->pCommonNextHash;
     1142    else
     1143    {
     1144        PSUPDRVSESSION pPrev = pCur;
     1145        while (pCur && pCur != pSession)
     1146        {
     1147            pPrev = pCur;
     1148            pCur  = pCur->pCommonNextHash;
     1149        }
     1150        if (pCur)
     1151            pPrev->pCommonNextHash = pCur->pCommonNextHash;
     1152        else
     1153        {
     1154            Assert(!pSession->fInHashTable);
     1155            RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
     1156            return VERR_NOT_FOUND;
     1157        }
     1158    }
     1159
     1160    pSession->pCommonNextHash = NULL;
     1161    pSession->fInHashTable    = false;
     1162
     1163    ASMAtomicDecU32(&pDevExt->cSessions);
     1164
     1165    /*
     1166     * Clear OS specific session pointer if available and do the OS callback.
     1167     */
     1168    if (pSession->ppOsSessionPtr)
     1169    {
     1170        ASMAtomicCmpXchgPtr(pSession->ppOsSessionPtr, NULL, pSession);
     1171        pSession->ppOsSessionPtr = NULL;
     1172    }
     1173
     1174    supdrvOSSessionHashTabRemoved(pDevExt, pSession, pvUser);
     1175
     1176    RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
     1177
     1178    /*
     1179     * Drop the reference the hash table had to the session.  This shouldn't
     1180     * be the last reference!
     1181     */
     1182    cRefs = ASMAtomicDecU32(&pSession->cRefs);
     1183    Assert(cRefs > 0 && cRefs < _1M);
     1184    if (cRefs == 0)
     1185        supdrvDestroySession(pDevExt, pSession);
     1186
     1187    return VINF_SUCCESS;
     1188}
     1189
     1190
     1191/**
     1192 * Looks up the session for the current process in the global hash table or in
     1193 * OS specific pointer.
     1194 *
     1195 * @returns Pointer to the session with a reference that the caller must
     1196 *          release.  If no valid session was found, NULL is returned.
     1197 *
     1198 * @param   pDevExt         The device extension.
     1199 * @param   Process         The process ID.
     1200 * @param   R0Process       The ring-0 process handle.
     1201 * @param   ppOsSessionPtr  The OS session pointer if available.  If not NULL,
     1202 *                          this is used instead of the hash table.  For
     1203 *                          additional safety it must then be equal to the
     1204 *                          SUPDRVSESSION::ppOsSessionPtr member.
     1205 *                          This can be NULL even if the OS has a session
     1206 *                          pointer.
     1207 */
     1208PSUPDRVSESSION VBOXCALL supdrvSessionHashTabLookup(PSUPDRVDEVEXT pDevExt, RTPROCESS Process, RTR0PROCESS R0Process,
     1209                                                   PSUPDRVSESSION *ppOsSessionPtr)
     1210{
     1211    PSUPDRVSESSION  pCur;
     1212    unsigned        iHash;
     1213
     1214    /*
     1215     * Validate input.
     1216     */
     1217    AssertReturn(R0Process != NIL_RTR0PROCESS, NULL);
     1218
     1219    /*
     1220     * Calculate the hash table index and acquire the spinlock.
     1221     */
     1222    iHash = SUPDRV_SESSION_HASH(Process);
     1223
     1224    RTSpinlockAcquire(pDevExt->hSessionHashTabSpinlock);
     1225
     1226    /*
     1227     * If an OS session pointer is provided, always use it.
     1228     */
     1229    if (ppOsSessionPtr)
     1230    {
     1231        pCur = *ppOsSessionPtr;
     1232        if (   pCur
     1233            && (   pCur->ppOsSessionPtr != ppOsSessionPtr
     1234                || pCur->Process        != Process
     1235                || pCur->R0Process      != R0Process) )
     1236            pCur = NULL;
     1237    }
     1238    else
     1239    {
     1240        /*
     1241         * Otherwise, do the hash table lookup.
     1242         */
     1243        pCur = pDevExt->apSessionHashTab[iHash];
     1244        while (   pCur
     1245               && (   pCur->Process   != Process
     1246                   || pCur->R0Process != R0Process) )
     1247            pCur = pCur->pCommonNextHash;
     1248    }
     1249
     1250    /*
     1251     * Retain the session.
     1252     */
     1253    if (pCur)
     1254    {
     1255        uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
     1256        Assert(cRefs > 1 && cRefs < _1M);
     1257    }
     1258
     1259    RTSpinlockRelease(pDevExt->hSessionHashTabSpinlock);
     1260
     1261    return pCur;
    9891262}
    9901263
     
    10231296    AssertMsg(cRefs < _1M, ("%#x %p\n", cRefs, pSession));
    10241297    if (cRefs == 0)
    1025         supdrvCloseSession(pSession->pDevExt, pSession);
     1298        supdrvDestroySession(pSession->pDevExt, pSession);
    10261299    return cRefs;
    10271300}
  • trunk/src/VBox/HostDrivers/Support/SUPDrvInternal.h

    r49965 r51770  
    5959#       define _interlockedbittestandreset64  _interlockedbittestandreset64_StupidDDKVsCompilerCrap
    6060#       pragma warning(disable : 4163)
    61 #       include <ntddk.h>
     61#       include <iprt/nt/nt.h>
    6262#       pragma warning(default : 4163)
    6363#       undef  _InterlockedExchange
     
    7070#       undef  _interlockedbittestandreset64
    7171#   else
    72 #       include <ntddk.h>
     72#       include <iprt/nt/nt.h>
    7373#   endif
    7474#   include <memory.h>
     
    177177 */
    178178#define OSDBGPRINT(a) SUPR0Printf a
     179
     180/** Debug printf macro shared with the ring-3 part. */
     181#ifdef DEBUG_bird
     182# define SUP_DPRINTF(a) SUPR0Printf a
     183#else
     184# define SUP_DPRINTF(a) do { } while (0)
     185#endif
    179186
    180187
     
    435442    /** Set if is an unrestricted session, clear if restricted. */
    436443    bool                            fUnrestricted;
    437     /* Reference counter. */
     444
     445    /** Set if we're in the hash table, clear if not.  Protected by the hash
     446     * table spinlock. */
     447    bool                            fInHashTable;
     448    /** Reference counter. */
    438449    uint32_t volatile               cRefs;
     450    /** Pointer to the next session with the same hash (common hash table).
     451     *  Protected by the hash table spinlock. */
     452    PSUPDRVSESSION                  pCommonNextHash;
     453    /** Pointer to the OS specific session pointer, if available and in use.
     454     * This is atomically set and cleared as the session is inserted and removed
     455     * from the hash table (protected by the session hash table spinlock). */
     456    PSUPDRVSESSION                 *ppOsSessionPtr;
     457    /** The process (id) of the session. */
     458    RTPROCESS                       Process;
     459    /** Which process this session is associated with.
     460     * This is NIL_RTR0PROCESS for kernel sessions and valid for user ones. */
     461    RTR0PROCESS                     R0Process;
    439462
    440463    /** The VM associated with the session. */
     
    446469    PSUPDRVLDRUSAGE volatile        pLdrUsage;
    447470
    448     /** Spinlock protecting the bundles and the GIP members. */
     471    /** Spinlock protecting the bundles, the GIP members and the
     472     * fProcessCleanupDone flag.  It continues to be valid until the last
     473     * reference to the session is released. */
    449474    RTSPINLOCK                      Spinlock;
    450475    /** The ring-3 mapping of the GIP (readonly). */
     
    461486    /** The group id of the session. (Set by the OS part.) */
    462487    RTGID                           Gid;
    463     /** The process (id) of the session. */
    464     RTPROCESS                       Process;
    465     /** Which process this session is associated with.
    466      * This is NIL_RTR0PROCESS for kernel sessions and valid for user ones. */
    467     RTR0PROCESS                     R0Process;
    468488    /** Per session tracer specfic data. */
    469489    uintptr_t                       uTracerData;
     
    498518    PSUPDRVSESSION                  pNextHash;
    499519# endif
     520# if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
     521    /** Pointer to the process protection structure for this session. */
     522    struct SUPDRVNTPROTECT         *pNtProtect;
     523# endif
    500524#endif /* !SUPDRV_AGNOSTIC */
    501525} SUPDRVSESSION;
     
    613637    RTLISTANCHOR                    aTrackerUmodHash[128];
    614638
     639    /** @name Session Handle Table.
     640     * @{ */
     641    /** Spinlock protecting apSessionHashTab, cSessions,
     642     * SUPDRVSESSION::ppOsSessionPtr, SUPDRVSESSION::pCommonNextHash, and possibly
     643     * others depending on the OS. */
     644    RTSPINLOCK                      hSessionHashTabSpinlock;
     645    /** Session hash table hash table.  The size of this table must make sense in
     646     * comparison to GVMM_MAX_HANDLES. */
     647    PSUPDRVSESSION                  apSessionHashTab[HC_ARCH_BITS == 64 ? 8191 : 127];
     648    /** The number of open sessions. */
     649    int32_t                         cSessions;
     650    /** @} */
     651
    615652    /*
    616      * Note! The non-agnostic bits must be a the very end of the structure!
     653     * Note! The non-agnostic bits must be at the very end of the structure!
    617654     */
    618655#ifndef SUPDRV_AGNOSTIC
     
    626663} SUPDRVDEVEXT;
    627664
     665/** Calculates the index into g_apSessionHashTab.*/
     666#define SUPDRV_SESSION_HASH(a_pid)     ( (a_pid) % RT_ELEMENTS(((SUPDRVDEVEXT *)NULL)->apSessionHashTab) )
     667
    628668
    629669RT_C_DECLS_BEGIN
     
    632672*   OS Specific Functions                                                      *
    633673*******************************************************************************/
     674/**
     675 * Called to clean up the session structure before it's freed.
     676 *
     677 * @param   pDevExt             The device globals.
     678 * @param   pSession            The session that's being cleaned up.
     679 */
     680void VBOXCALL   supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession);
     681
     682/**
     683 * Called to let the OS specfic code perform additional insertion work while
     684 * still under the protection of the hash table spinlock.
     685 *
     686 * @param   pDevExt             The device globals.
     687 * @param   pSession            The session that was inserted.
     688 * @param   pvUser              User context specified to the insert call.
     689 */
     690void VBOXCALL   supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser);
     691
     692/**
     693 * Called to let the OS specfic code perform additional removal work while still
     694 * under the protection of the hash table spinlock.
     695 *
     696 * @param   pDevExt             The device globals.
     697 * @param   pSession            The session that was removed.
     698 * @param   pvUser              User context specified to the remove call.
     699 */
     700void VBOXCALL   supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser);
     701
    634702void VBOXCALL   supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession);
    635703bool VBOXCALL   supdrvOSObjCanAccess(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession, const char *pszObjName, int *prc);
     
    763831void VBOXCALL   supdrvDeleteDevExt(PSUPDRVDEVEXT pDevExt);
    764832int  VBOXCALL   supdrvCreateSession(PSUPDRVDEVEXT pDevExt, bool fUser, bool fUnrestricted,  PSUPDRVSESSION *ppSession);
     833int  VBOXCALL   supdrvSessionHashTabInsert(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, PSUPDRVSESSION *ppOsSessionPtr, void *pvUser);
     834int  VBOXCALL   supdrvSessionHashTabRemove(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser);
     835PSUPDRVSESSION VBOXCALL supdrvSessionHashTabLookup(PSUPDRVDEVEXT pDevExt, RTPROCESS Process, RTR0PROCESS R0Process,
     836                                                   PSUPDRVSESSION *ppOsSessionPtr);
    765837uint32_t VBOXCALL supdrvSessionRetain(PSUPDRVSESSION pSession);
    766838uint32_t VBOXCALL supdrvSessionRelease(PSUPDRVSESSION pSession);
  • trunk/src/VBox/HostDrivers/Support/SUPLib.cpp

    r49965 r51770  
    15421542     * Verify that the image file and parent directories are sane.
    15431543     */
    1544     rc = supR3HardenedVerifyFile(szExecPath, RTHCUINTPTR_MAX, pErrInfo);
     1544    rc = supR3HardenedVerifyFile(szExecPath, RTHCUINTPTR_MAX, false /*fMaybe3rdParty*/, pErrInfo);
    15451545    if (RT_FAILURE(rc))
    15461546        return rc;
     
    15861586     */
    15871587#ifdef VBOX_WITH_HARDENING
    1588     int rc = supR3HardenedVerifyFile(pszFilename, RTHCUINTPTR_MAX, pErrInfo);
     1588    int rc = supR3HardenedVerifyFile(pszFilename, RTHCUINTPTR_MAX, true /*fMaybe3rdParty*/, pErrInfo);
    15891589    if (RT_FAILURE(rc) && !RTErrInfoIsSet(pErrInfo))
    15901590        LogRel(("supR3HardenedVerifyFile: Verification of \"%s\" failed, rc=%Rrc\n", pszFilename, rc));
  • trunk/src/VBox/HostDrivers/Support/SUPLibInternal.h

    r49634 r51770  
    104104 */
    105105#if defined(IN_SUP_HARDENED_R3) && defined(RT_OS_WINDOWS)
     106# define SUP_HARDENED_NEED_CRT_FUNCTIONS
     107DECLHIDDEN(int)    suplibHardenedMemComp(void const *pvDst, const void *pvSrc, size_t cbToComp);
    106108DECLHIDDEN(void *) suplibHardenedMemCopy(void *pvDst, const void *pvSrc, size_t cbToCopy);
     109DECLHIDDEN(void *) suplibHardenedMemSet(void *pvDst, int ch, size_t cbToSet);
    107110DECLHIDDEN(char *) suplibHardenedStrCopy(char *pszDst, const char *pszSrc);
    108111DECLHIDDEN(size_t) suplibHardenedStrLen(const char *psz);
     
    112115DECLHIDDEN(int)    suplibHardenedStrICmp(const char *psz1, const char *psz2);
    113116#else
     117# undef SUP_HARDENED_NEED_CRT_FUNCTIONS
     118# define suplibHardenedMemComp memcmp
    114119# define suplibHardenedMemCopy memcpy
     120# define suplibHardenedMemSet  memset
    115121# define suplibHardenedStrCopy strcpy
    116122# define suplibHardenedStrLen  strlen
     
    120126# define suplibHardenedStrICmp stricmp
    121127#endif
    122 DECLNORETURN(void) suplibHardenedExit(RTEXITCODE rcExit);
     128DECLNORETURN(void)  suplibHardenedExit(RTEXITCODE rcExit);
     129DECLHIDDEN(void)    suplibHardenedPrintF(const char *pszFormat, ...);
     130DECLHIDDEN(void)    suplibHardenedPrintFV(const char *pszFormat, va_list va);
     131
    123132/** @} */
     133
     134/** Debug output macro. */
     135#ifdef DEBUG_bird
     136# ifdef IN_SUP_HARDENED_R3
     137#  define SUP_DPRINTF(a)    suplibHardenedPrintF a
     138# else
     139#  define SUP_DPRINTF(a)    RTLogPrintf a
     140# endif
     141#else
     142# define SUP_DPRINTF(a)     do { } while (0)
     143#endif
    124144
    125145
     
    135155    kSupIFT_Exe,
    136156    kSupIFT_Dll,
     157    kSupIFT_Rc,
    137158    kSupIFT_Sys,
    138159    kSupIFT_Script,
     
    276297typedef FNSUPR3PREINIT *PFNSUPR3PREINIT;
    277298
     299/** The current SUPR3HardenedMain state / location. */
     300typedef enum SUPR3HARDENEDMAINSTATE
     301{
     302    SUPR3HARDENEDMAINSTATE_NOT_YET_CALLED = 0,
     303    SUPR3HARDENEDMAINSTATE_VERIFY_TRUST_READY,
     304    SUPR3HARDENEDMAINSTATE_INIT_RUNTIME,
     305    SUPR3HARDENEDMAINSTATE_GET_TRUSTED_MAIN,
     306    SUPR3HARDENEDMAINSTATE_CALLED_TRUSTED_MAIN,
     307    SUPR3HARDENEDMAINSTATE_END
     308} SUPR3HARDENEDMAINSTATE;
     309
    278310
    279311/*******************************************************************************
     
    288320extern DECLHIDDEN(PSUPQUERYFUNCS)       g_pSupFunctions;
    289321#endif
     322extern DECLHIDDEN(SUPR3HARDENEDMAINSTATE) g_enmSupR3HardenedMainState;
    290323
    291324
     
    360393 */
    361394DECLHIDDEN(int)     supR3HardenedError(int rc, bool fFatal, const char *pszFormat, ...);
     395
    362396DECLHIDDEN(int)     supR3HardenedVerifyAll(bool fFatal, bool fLeaveFilesOpen, const char *pszProgName);
    363397DECLHIDDEN(int)     supR3HardenedVerifyFixedDir(SUPINSTDIR enmDir, bool fFatal);
    364398DECLHIDDEN(int)     supR3HardenedVerifyFixedFile(const char *pszFilename, bool fFatal);
    365399DECLHIDDEN(int)     supR3HardenedVerifyDir(const char *pszDirPath, bool fRecursive, bool fCheckFiles, PRTERRINFO pErrInfo);
    366 DECLHIDDEN(int)     supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile, PRTERRINFO pErrInfo);
     400DECLHIDDEN(int)     supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile, bool fMaybe3rdParty,
     401                                            PRTERRINFO pErrInfo);
    367402DECLHIDDEN(void)    supR3HardenedGetPreInitData(PSUPPREINITDATA pPreInitData);
    368403DECLHIDDEN(int)     supR3HardenedRecvPreInitData(PCSUPPREINITDATA pPreInitData);
    369404
     405#ifdef RT_OS_WINDOWS
     406DECLHIDDEN(void)    supR3HardenedWinInit(uint32_t fFlags);
     407DECLHIDDEN(void)    supR3HardenedWinInitVersion(void);
     408DECLHIDDEN(void)    supR3HardenedWinVerifyProcess(void);
     409DECLHIDDEN(void)    supR3HardenedWinResolveVerifyTrustApiAndHookThreadCreation(void);
     410DECLHIDDEN(bool)    supR3HardenedWinIsReSpawnNeeded(int cArgs, char **papszArgs);
     411DECLHIDDEN(int)     supR3HardenedWinReSpawn(void);
     412DECLHIDDEN(void *)  supR3HardenedWinLoadLibrary(const char *pszName, bool fSystem32Only);
     413extern RTUTF16      g_wszSupLibHardenedExePath[1024];
     414# ifdef RTPATH_MAX
     415extern char         g_szSupLibHardenedExePath[RTPATH_MAX];
     416# endif
     417#endif
    370418
    371419SUPR3DECL(int)      supR3PageLock(void *pvStart, size_t cPages, PSUPPAGE paPages);
  • trunk/src/VBox/HostDrivers/Support/SUPLibLdr.cpp

    r49634 r51770  
    781781     * Verify the image file.
    782782     */
    783     int rc = supR3HardenedVerifyFile(pszFilename, RTHCUINTPTR_MAX, pErrInfo);
     783    int rc = supR3HardenedVerifyFile(pszFilename, RTHCUINTPTR_MAX, true /*fMaybe3rdParty*/, pErrInfo);
    784784    if (RT_FAILURE(rc))
    785785    {
  • trunk/src/VBox/HostDrivers/Support/SUPR3HardenedMain.cpp

    r49500 r51770  
    55
    66/*
    7  * Copyright (C) 2006-2013 Oracle Corporation
     7 * Copyright (C) 2006-2014 Oracle Corporation
    88 *
    99 * This file is part of VirtualBox Open Source Edition (OSE), as
     
    121121*******************************************************************************/
    122122/** The pre-init data we pass on to SUPR3 (residing in VBoxRT). */
    123 static SUPPREINITDATA g_SupPreInitData;
     123static SUPPREINITDATA   g_SupPreInitData;
    124124/** The program executable path. */
    125 static char g_szSupLibHardenedExePath[RTPATH_MAX];
     125#ifndef RT_OS_WINDOWS
     126static
     127#endif
     128char                    g_szSupLibHardenedExePath[RTPATH_MAX];
    126129/** The program directory path. */
    127 static char g_szSupLibHardenedDirPath[RTPATH_MAX];
     130static char             g_szSupLibHardenedDirPath[RTPATH_MAX];
    128131
    129132/** The program name. */
    130 static const char *g_pszSupLibHardenedProgName;
     133static const char      *g_pszSupLibHardenedProgName;
    131134
    132135#ifdef SUP_HARDENED_SUID
    133136/** The real UID at startup. */
    134 static uid_t g_uid;
     137static uid_t            g_uid;
    135138/** The real GID at startup. */
    136 static gid_t g_gid;
     139static gid_t            g_gid;
    137140# ifdef RT_OS_LINUX
    138 static uint32_t g_uCaps;
     141static uint32_t         g_uCaps;
    139142# endif
    140143#endif
     144
     145/** The current SUPR3HardenedMain state / location. */
     146SUPR3HARDENEDMAINSTATE  g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_NOT_YET_CALLED;
    141147
    142148
     
    148154#endif
    149155static PFNSUPTRUSTEDERROR supR3HardenedMainGetTrustedError(const char *pszProgName);
    150 
    151 
    152 #ifdef RT_OS_WINDOWS
    153 /*
    154  * No CRT here, thank you.
    155  */
    156 
    157 /** memcpy */
    158 DECLHIDDEN(void *) suplibHardenedMemCopy(void *pvDst, const void *pvSrc, size_t cbToCopy)
    159 {
    160     size_t         *puDst = (size_t *)pvDst;
    161     size_t const   *puSrc = (size_t const *)pvSrc;
    162     while (cbToCopy >= sizeof(size_t))
    163     {
    164         *puDst++ = *puSrc++;
    165         cbToCopy -= sizeof(size_t);
    166     }
    167 
    168     uint8_t        *pbDst = (uint8_t *)puDst;
    169     uint8_t const  *pbSrc = (uint8_t const *)puSrc;
    170     while (cbToCopy > 0)
    171     {
    172         *pbDst++ = *pbSrc++;
    173         cbToCopy--;
    174     }
    175 
    176     return pvDst;
    177 }
    178 
    179 
    180 /** strcpy */
    181 DECLHIDDEN(char *) suplibHardenedStrCopy(char *pszDst, const char *pszSrc)
    182 {
    183     char *pszRet = pszDst;
    184     char ch;
    185     do
    186     {
    187         ch = *pszSrc++;
    188         *pszDst++ = ch;
    189     } while (ch);
    190     return pszRet;
    191 }
    192 
    193 
    194 /** strlen */
    195 DECLHIDDEN(size_t) suplibHardenedStrLen(const char *psz)
    196 {
    197     const char *pszStart = psz;
    198     while (*psz)
    199         psz++;
    200     return psz - pszStart;
    201 }
    202 
    203 
    204 /** strcat */
    205 DECLHIDDEN(char *) suplibHardenedStrCat(char *pszDst, const char *pszSrc)
    206 {
    207     char *pszRet = pszDst;
    208     while (*pszDst)
    209         pszDst++;
    210     suplibHardenedStrCopy(pszDst, pszSrc);
    211     return pszRet;
    212 }
    213 
    214 
    215 # ifdef RT_OS_WINDOWS
    216 /** stricmp */
    217 DECLHIDDEN(int) suplibHardenedStrICmp(const char *psz1, const char *psz2)
    218 {
    219     const char *pszOrg1 = psz1;
    220     const char *pszOrg2 = psz2;
    221 
    222     for (;;)
    223     {
    224         char ch1 = *psz1++;
    225         char ch2 = *psz1++;
    226         if (ch1 != ch2)
    227         {
    228             int rc = CompareStringA(LOCALE_USER_DEFAULT, NORM_IGNORECASE, pszOrg1, -1, pszOrg2, -1);
    229 #  ifdef VBOX_STRICT
    230             if (rc == 0)
    231                 __debugbreak();
    232 #  endif
    233             return rc - 2;
    234         }
    235         if (ch1 == 0)
    236             return 0;
    237     }
    238 }
    239 # endif
    240 
    241 
    242 /** strcmp */
    243 DECLHIDDEN(int) suplibHardenedStrCmp(const char *psz1, const char *psz2)
    244 {
    245     for (;;)
    246     {
    247         char ch1 = *psz1++;
    248         char ch2 = *psz1++;
    249         if (ch1 != ch2)
    250             return ch1 < ch2 ? -1 : 1;
    251         if (ch1 == 0)
    252             return 0;
    253     }
    254 }
    255 
    256 
    257 /** strncmp */
    258 DECLHIDDEN(int) suplibHardenedStrNCmp(const char *psz1, const char *psz2, size_t cchMax)
    259 {
    260     while (cchMax-- > 0)
    261     {
    262         char ch1 = *psz1++;
    263         char ch2 = *psz1++;
    264         if (ch1 != ch2)
    265             return ch1 < ch2 ? -1 : 1;
    266         if (ch1 == 0)
    267             break;
    268     }
    269     return 0;
    270 }
    271 
    272 #endif /* RT_OS_WINDOWS */
    273156
    274157
     
    423306    do
    424307    {
    425         unsigned iDigit = uValue & fDigitMask;
     308        *psz-- = pchDigits[uValue & fDigitMask];
    426309        uValue >>= cShift;
    427 
    428         *psz-- = uValue % 10;
    429         uValue /= 10;
    430310    } while (uValue > 0);
    431311
    432312    if ((fFlags & RTSTR_F_SPECIAL) && uBase == 16)
    433313    {
    434         *psz-- = 'x';
     314        *psz-- = !(fFlags & RTSTR_F_CAPITAL) ? 'x' : 'X';
    435315        *psz-- = '0';
    436316    }
     
    442322
    443323/**
     324 * Writes a wide character string to standard error.
     325 *
     326 * @param   pwsz                The string.
     327 */
     328static void suplibHardenedPrintWideStr(PCRTUTF16 pwsz)
     329{
     330    for (;;)
     331    {
     332        RTUTF16 wc = *pwsz++;
     333        if (!wc)
     334            return;
     335        if (   (wc < 0x7f && wc >= 0x20)
     336            || wc == '\n'
     337            || wc == '\r')
     338            suplibHardenedPrintChr((char)wc);
     339        else
     340        {
     341            suplibHardenedPrintStrN(RT_STR_TUPLE("\\x"));
     342            suplibHardenedPrintHexOctal(wc, 16, 0);
     343        }
     344    }
     345}
     346
     347#ifdef IPRT_NO_CRT
     348
     349/** Buffer structure used by suplibHardenedOutput. */
     350struct SUPLIBHARDENEDOUTPUTBUF
     351{
     352    size_t off;
     353    char   szBuf[2048];
     354};
     355
     356/** Callback for RTStrFormatV, see FNRTSTROUTPUT. */
     357static DECLCALLBACK(size_t) suplibHardenedOutput(void *pvArg, const char *pachChars, size_t cbChars)
     358{
     359    SUPLIBHARDENEDOUTPUTBUF *pBuf = (SUPLIBHARDENEDOUTPUTBUF *)pvArg;
     360    size_t cbTodo = cbChars;
     361    for (;;)
     362    {
     363        size_t cbSpace = sizeof(pBuf->szBuf) - pBuf->off - 1;
     364
     365        /* Flush the buffer? */
     366        if (   cbSpace == 0
     367            || (cbTodo == 0 && pBuf->off))
     368        {
     369            suplibHardenedPrintStrN(pBuf->szBuf, pBuf->off);
     370# ifdef RT_OS_WINDOWS
     371            OutputDebugString(pBuf->szBuf);
     372# endif
     373            pBuf->off = 0;
     374            cbSpace = sizeof(pBuf->szBuf) - 1;
     375        }
     376
     377        /* Copy the string into the buffer. */
     378        if (cbTodo == 1)
     379        {
     380            pBuf->szBuf[pBuf->off++] = *pachChars;
     381            break;
     382        }
     383        if (cbSpace >= cbTodo)
     384        {
     385            memcpy(&pBuf->szBuf[pBuf->off], pachChars, cbTodo);
     386            pBuf->off += cbTodo;
     387            break;
     388        }
     389        memcpy(&pBuf->szBuf[pBuf->off], pachChars, cbSpace);
     390        pBuf->off += cbSpace;
     391        cbTodo -= cbSpace;
     392    }
     393    pBuf->szBuf[pBuf->off] = '\0';
     394
     395    return cbChars;
     396}
     397
     398#endif /* IPRT_NO_CRT */
     399
     400/**
    444401 * Simple printf to standard error.
    445402 *
     
    449406DECLHIDDEN(void) suplibHardenedPrintFV(const char *pszFormat, va_list va)
    450407{
     408#ifdef IPRT_NO_CRT
     409    /*
     410     * Use buffered output here to avoid character mixing on the windows
     411     * console and to enable us to use OutputDebugString.
     412     */
     413    SUPLIBHARDENEDOUTPUTBUF Buf;
     414    Buf.off = 0;
     415    Buf.szBuf[0] = '\0';
     416    RTStrFormatV(suplibHardenedOutput, &Buf, NULL, NULL, pszFormat, va);
     417
     418#else /* !IPRT_NO_CRT */
    451419    /*
    452420     * Format loop.
     
    544512
    545513                case 's':
    546                 {
    547                     const char *pszStr = va_arg(va, const char *);
    548                     if (!RT_VALID_PTR(pszStr))
    549                         pszStr = "<NULL>";
    550                     suplibHardenedPrintStr(pszStr);
     514                    if (chArgSize == 'l')
     515                    {
     516                        PCRTUTF16 pwszStr = va_arg(va, PCRTUTF16 );
     517                        if (RT_VALID_PTR(pwszStr))
     518                            suplibHardenedPrintWideStr(pwszStr);
     519                        else
     520                            suplibHardenedPrintStr("<NULL>");
     521                    }
     522                    else
     523                    {
     524                        const char *pszStr = va_arg(va, const char *);
     525                        if (!RT_VALID_PTR(pszStr))
     526                            pszStr = "<NULL>";
     527                        suplibHardenedPrintStr(pszStr);
     528                    }
    551529                    break;
    552                 }
    553530
    554531                case 'd':
     
    617594                }
    618595
     596                case 'R':
     597                    if (pszFormat[0] == 'r' && pszFormat[1] == 'c')
     598                    {
     599                        int iValue = va_arg(va, int);
     600                        if (iValue < 0)
     601                        {
     602                            suplibHardenedPrintChr('-');
     603                            iValue = -iValue;
     604                        }
     605                        suplibHardenedPrintDecimal(iValue);
     606                        pszFormat += 2;
     607                        break;
     608                    }
     609                    /* fall thru */
    619610
    620611                /*
     
    636627    if (pszLast != pszFormat)
    637628        suplibHardenedPrintStrN(pszLast, pszFormat - pszLast);
     629#endif /* !IPRT_NO_CRT */
    638630}
    639631
     
    652644    va_end(va);
    653645}
    654 
    655646
    656647
     
    863854
    864855#elif defined(RT_OS_WINDOWS)
    865     HMODULE hExe = GetModuleHandle(NULL);
    866     if (!GetModuleFileName(hExe, &g_szSupLibHardenedExePath[0], sizeof(g_szSupLibHardenedExePath)))
    867         supR3HardenedFatal("supR3HardenedExecDir: GetModuleFileName failed, rc=%d\n", GetLastError());
     856    int cbRet = WideCharToMultiByte(CP_UTF8, 0 /*dwFlags*/,
     857                                    g_wszSupLibHardenedExePath, -1,
     858                                    g_szSupLibHardenedExePath, sizeof(g_szSupLibHardenedExePath),
     859                                    NULL /*pchDefChar*/, NULL /* pfUsedDefChar */);
     860    if (!cbRet)
     861        supR3HardenedFatal("supR3HardenedExecDir: WideCharToMultiByte failed, rc=%d\n", GetLastError());
    868862#else
    869863# error needs porting.
     
    956950            break;
    957951
     952        case kSupInitOp_Misc:
    958953        case kSupInitOp_IPRT:
    959954        case kSupInitOp_Integrity:
     
    988983#endif
    989984    {
    990         PFNSUPTRUSTEDERROR pfnTrustedError = supR3HardenedMainGetTrustedError(g_pszSupLibHardenedProgName);
    991         if (pfnTrustedError)
    992             pfnTrustedError(pszWhere, enmWhat, rc, pszMsgFmt, va);
     985        static volatile bool s_fRecursive = false; /* Loader hooks may cause recursion. */
     986        if (!s_fRecursive)
     987        {
     988            s_fRecursive = true;
     989
     990            PFNSUPTRUSTEDERROR pfnTrustedError = supR3HardenedMainGetTrustedError(g_pszSupLibHardenedProgName);
     991            if (pfnTrustedError)
     992                pfnTrustedError(pszWhere, enmWhat, rc, pszMsgFmt, va);
     993
     994            s_fRecursive = false;
     995        }
    993996    }
    994997
     
    10821085            supR3HardenedFatalMsg("suplibOsInit", kSupInitOp_Driver, rc,
    10831086                                  "Kernel memory allocation/mapping failed");
     1087        case VERR_SUPDRV_HARDENING_EVIL_HANDLE:
     1088            supR3HardenedFatalMsg("suplibOsInit", kSupInitOp_Driver, rc, "VERR_SUPDRV_HARDENING_EVIL_HANDLE");
     1089        case VERR_SUPLIB_NT_PROCESS_UNTRUSTED_0:
     1090            supR3HardenedFatalMsg("suplibOsInit", kSupInitOp_Driver, rc, "VERR_SUPLIB_NT_PROCESS_UNTRUSTED_0");
     1091        case VERR_SUPLIB_NT_PROCESS_UNTRUSTED_1:
     1092            supR3HardenedFatalMsg("suplibOsInit", kSupInitOp_Driver, rc, "VERR_SUPLIB_NT_PROCESS_UNTRUSTED_1");
     1093        case VERR_SUPLIB_NT_PROCESS_UNTRUSTED_2:
     1094            supR3HardenedFatalMsg("suplibOsInit", kSupInitOp_Driver, rc, "VERR_SUPLIB_NT_PROCESS_UNTRUSTED_2");
    10841095        default:
    10851096            supR3HardenedFatalMsg("suplibOsInit", kSupInitOp_Driver, rc,
     
    13251336     */
    13261337#if defined(RT_OS_WINDOWS)
    1327     /** @todo consider using LOAD_WITH_ALTERED_SEARCH_PATH here! */
    1328     HMODULE hMod = LoadLibraryEx(szPath, NULL /*hFile*/, 0 /* dwFlags */);
     1338    HMODULE hMod = (HMODULE)supR3HardenedWinLoadLibrary(szPath, false /*fSystem32Only*/);
    13291339    if (!hMod)
    13301340        supR3HardenedFatalMsg("supR3HardenedMainInitRuntime", kSupInitOp_IPRT, VERR_MODULE_NOT_FOUND,
    1331                               "LoadLibraryEx(\"%s\",,) failed (rc=%d)",
     1341                              "LoadLibrary \"%s\" failed (rc=%d)",
    13321342                              szPath, GetLastError());
    13331343    PFNRTR3INITEX pfnRTInitEx = (PFNRTR3INITEX)GetProcAddress(hMod, SUP_HARDENED_SYM("RTR3InitEx"));
     
    14081418     */
    14091419#if defined(RT_OS_WINDOWS)
    1410     /** @todo consider using LOAD_WITH_ALTERED_SEARCH_PATH here! */
    1411     HMODULE hMod = LoadLibraryEx(szPath, NULL /*hFile*/, 0 /* dwFlags */);
     1420    HMODULE hMod = (HMODULE)supR3HardenedWinLoadLibrary(szPath, false /*fSystem32Only*/);
    14121421    if (!hMod)
    14131422        return NULL;
     
    14521461     */
    14531462#if defined(RT_OS_WINDOWS)
    1454     /** @todo consider using LOAD_WITH_ALTERED_SEARCH_PATH here! */
    1455     HMODULE hMod = LoadLibraryEx(szPath, NULL /*hFile*/, 0 /* dwFlags */);
     1463    HMODULE hMod = (HMODULE)supR3HardenedWinLoadLibrary(szPath, false /*fSystem32Only*/);
    14561464    if (!hMod)
    1457         supR3HardenedFatal("supR3HardenedMainGetTrustedMain: LoadLibraryEx(\"%s\",,) failed, rc=%d\n",
     1465        supR3HardenedFatal("supR3HardenedMainGetTrustedMain: LoadLibrary \"%s\" failed, rc=%d\n",
    14581466                            szPath, GetLastError());
    14591467    FARPROC pfn = GetProcAddress(hMod, SUP_HARDENED_SYM("TrustedMain"));
     
    15361544
    15371545    /*
    1538      * Validate the installation.
    1539      */
     1546     * Validate the installation.  On Windows we leave the files open so they
     1547     * cannot be tampered with after they've been verified.  We also check
     1548     * install loader hooks and check the process integrity.
     1549     */
     1550#ifndef RT_OS_WINDOWS
    15401551    supR3HardenedVerifyAll(true /* fFatal */, false /* fLeaveFilesOpen */, pszProgName);
     1552#else
     1553    supR3HardenedWinInit(fFlags);
     1554    supR3HardenedVerifyAll(true /* fFatal */, true /* fLeaveFilesOpen */, pszProgName);
     1555    supR3HardenedWinVerifyProcess();
     1556#endif
     1557
     1558#ifdef RT_OS_WINDOWS
     1559    /*
     1560     * On Windows we'll respawn the process with a special vboxdrv arrangement
     1561     * in place to monitor access to the process for its inception.
     1562     */
     1563    if (   !(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV)
     1564        && supR3HardenedWinIsReSpawnNeeded(argc, argv))
     1565        return supR3HardenedWinReSpawn();
     1566#endif
    15411567
    15421568    /*
     
    15451571    if (!(fFlags & SUPSECMAIN_FLAGS_DONT_OPEN_DEV))
    15461572        supR3HardenedMainOpenDevice();
     1573#ifdef RT_OS_WINDOWS
     1574    supR3HardenedWinResolveVerifyTrustApiAndHookThreadCreation();
     1575    g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_VERIFY_TRUST_READY;
     1576#endif
    15471577
    15481578    /*
     
    15681598     * call RTR3InitEx.
    15691599     */
     1600    g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_INIT_RUNTIME;
    15701601    supR3HardenedMainInitRuntime(fFlags);
    15711602
     
    15741605     * and pass control to it.
    15751606     */
     1607    g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_GET_TRUSTED_MAIN;
    15761608    PFNSUPTRUSTEDMAIN pfnTrustedMain = supR3HardenedMainGetTrustedMain(pszProgName);
     1609    g_enmSupR3HardenedMainState = SUPR3HARDENEDMAINSTATE_CALLED_TRUSTED_MAIN;
    15771610    return pfnTrustedMain(argc, argv, envp);
    15781611}
    15791612
    1580 
    1581 #ifdef RT_OS_WINDOWS
    1582 
    1583 extern "C" int main(int argc, char **argv, char **envp);
    1584 
    1585 /**
    1586  * The executable entry point.
    1587  */
    1588 extern "C" void __stdcall suplibHardenedWindowsMain(void)
    1589 {
    1590     RTEXITCODE  rcExit = RTEXITCODE_FAILURE;
    1591 
    1592     /*
    1593      * Convert the arguments to UTF-8.
    1594      */
    1595     int    cArgs;
    1596     PWSTR *papwszArgs = CommandLineToArgvW(GetCommandLineW(), &cArgs); /** @todo fix me! */
    1597     if (papwszArgs)
    1598     {
    1599         char **papszArgs = (char **)HeapAlloc(GetProcessHeap(), 0 /* dwFlags*/, (cArgs + 1) * sizeof(const char **));
    1600         if (papszArgs)
    1601         {
    1602             int iArg;
    1603             for (iArg = 0; iArg < cArgs; iArg++)
    1604             {
    1605                 int cbNeeded = WideCharToMultiByte(CP_UTF8, 0 /*dwFlags*/, papwszArgs[iArg], -1, NULL /*pszDst*/, 0 /*cbDst*/,
    1606                                                    NULL /*pchDefChar*/, NULL /* pfUsedDefChar */);
    1607                 if (!cbNeeded)
    1608                 {
    1609                     suplibHardenedPrintF("CommandLineToArgvW failed on argument %d: %u\n", iArg, GetLastError());
    1610                     break;
    1611                 }
    1612 
    1613                 papszArgs[iArg] = (char *)HeapAlloc(GetProcessHeap(), 0 /*dwFlags*/, cbNeeded);
    1614                 if (!papszArgs[iArg])
    1615                 {
    1616                     suplibHardenedPrintF("HeapAlloc failed");
    1617                     break;
    1618                 }
    1619 
    1620                 int cbRet = WideCharToMultiByte(CP_UTF8, 0 /*dwFlags*/, papwszArgs[iArg], -1, papszArgs[iArg], cbNeeded,
    1621                                                 NULL /*pchDefChar*/, NULL /* pfUsedDefChar */);
    1622                 if (!cbRet)
    1623                 {
    1624                     suplibHardenedPrintF("CommandLineToArgvW failed on argument %d: %u\n", iArg, GetLastError());
    1625                     break;
    1626                 }
    1627             }
    1628             if (iArg == cArgs)
    1629             {
    1630                 papszArgs[iArg] = NULL;
    1631 
    1632                 /*
    1633                  * Call the main function.
    1634                  */
    1635                 rcExit = (RTEXITCODE)main(cArgs, papszArgs, NULL);
    1636             }
    1637         }
    1638         else
    1639             suplibHardenedPrintF("HeapAlloc failed\n");
    1640     }
    1641     else
    1642         suplibHardenedPrintF("CommandLineToArgvW failed\n");
    1643 
    1644     /*
    1645      * Exit the process (never return).
    1646      */
    1647     for (;;)
    1648         ExitProcess(rcExit);
    1649 }
    1650 
    1651 #endif
  • trunk/src/VBox/HostDrivers/Support/SUPR3HardenedVerify.cpp

    r49211 r51770  
    7474
    7575#include "SUPLibInternal.h"
     76#if defined(RT_OS_WINDOWS) && defined(VBOX_WITH_HARDENING)
     77# define SUPHNTVI_NO_NT_STUFF
     78# include "win/SUPHardenedVerify-win.h"
     79#endif
    7680
    7781
     
    8690#endif
    8791
     92/** Compare table file names with externally supplied names. */
     93#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
     94# define SUP_COMP_FILENAME  suplibHardenedStrICmp
     95#else
     96# define SUP_COMP_FILENAME  suplibHardenedStrCmp
     97#endif
     98
    8899
    89100/*******************************************************************************
     
    107118
    108119#ifdef VBOX_WITH_RAW_MODE
    109     {   kSupIFT_Dll,  kSupID_AppPrivArch,       false, "VMMGC.gc" },
    110     {   kSupIFT_Dll,  kSupID_AppPrivArch,       false, "VBoxDDGC.gc" },
    111     {   kSupIFT_Dll,  kSupID_AppPrivArch,       false, "VBoxDD2GC.gc" },
     120    {   kSupIFT_Rc,   kSupID_AppPrivArch,       false, "VMMGC.gc" },
     121    {   kSupIFT_Rc,   kSupID_AppPrivArch,       false, "VBoxDDGC.gc" },
     122    {   kSupIFT_Rc,   kSupID_AppPrivArch,       false, "VBoxDD2GC.gc" },
    112123#endif
    113124
     
    154165    {   kSupIFT_Exe,  kSupID_AppBin,            false, "VBoxSVC" SUPLIB_EXE_SUFF },
    155166 #ifdef RT_OS_WINDOWS
    156     {   kSupIFT_Dll,  kSupID_AppPrivArchComp,   false, "VBoxC" SUPLIB_DLL_SUFF },
     167    {   kSupIFT_Dll,  kSupID_SharedLib,         false, "VBoxC" SUPLIB_DLL_SUFF },
    157168 #else
    158169    {   kSupIFT_Exe,  kSupID_AppPrivArch,       false, "VBoxXPCOMIPCD" SUPLIB_EXE_SUFF },
     
    347358                                 FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
    348359                                 NULL,
    349                                  OPEN_ALWAYS,
     360                                 OPEN_EXISTING,
    350361                                 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
    351362                                 NULL);
     
    466477        if (RT_SUCCESS(rc))
    467478        {
    468 #if defined(RT_OS_WINDOWS)
     479#if defined(RT_OS_WINDOWS) /** @todo Need to use WCHAR on windows! */
    469480            HANDLE hFile = CreateFile(szPath,
    470481                                      GENERIC_READ,
    471482                                      FILE_SHARE_READ,
    472483                                      NULL,
    473                                       OPEN_ALWAYS,
     484                                      OPEN_EXISTING,
    474485                                      FILE_ATTRIBUTE_NORMAL,
    475486                                      NULL);
    476487            if (hFile != INVALID_HANDLE_VALUE)
    477488            {
    478                 /** @todo Check the type, and verify the signature (separate function so we can skip it). */
     489# if defined(VBOX_WITH_HARDENING) && !defined(IN_SUP_R3_STATIC) /* Latter: Not in VBoxCpuReport and friends. */
     490
     491                char szErr[1024];
     492                RTERRINFO ErrInfo;
     493                RTErrInfoInit(&ErrInfo, szErr, sizeof(szErr));
     494
     495                uint32_t fFlags = SUPHNTVI_F_REQUIRE_BUILD_CERT;
     496                if (pFile->enmType == kSupIFT_Rc)
     497                    fFlags |= SUPHNTVI_F_RC_IMAGE;
     498
     499                rc = supHardenedWinVerifyImageByHandleNoName(hFile, fFlags, &ErrInfo);
     500                if (RT_FAILURE(rc))
     501                {
     502                    rc = supR3HardenedError(rc, fFatal, "supR3HardenedVerifyFileInternal: '%s': Image verify error rc=%Rrc: %s\n",
     503                                            szPath, rc, szErr);
     504                    CloseHandle(hFile);
     505                }
     506                else
     507#endif
    479508                {
    480509                    /* it's valid. */
     
    491520                if (!pFile->fOptional || err != ERROR_FILE_NOT_FOUND)
    492521                    rc = supR3HardenedError(VERR_PATH_NOT_FOUND, fFatal,
    493                                             "supR3HardenedVerifyFileInternal: Failed to open \"%s\": err=%d\n",
    494                                             szPath, err);
     522                                            "supR3HardenedVerifyFileInternal: Failed to open '%s': err=%d\n", szPath, err);
    495523            }
    496524#else /* UNIXY */
     
    581609    if (RT_FAILURE(rc))
    582610        return rc;
    583 #if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
    584     if (suplibHardenedStrICmp(szName, pszFilename))
    585 #else
    586     if (suplibHardenedStrCmp(szName, pszFilename))
    587 #endif
     611    if (SUP_COMP_FILENAME(szName, pszFilename))
    588612    {
    589613        /*
     
    596620        if (    GetFullPathName(szName, RT_ELEMENTS(szName2), &szName2[0], &pszIgnored)
    597621            &&  GetFullPathName(pszFilename, RT_ELEMENTS(szName), &szName[0], &pszIgnored))
    598             if (!suplibHardenedStrICmp(szName2, szName))
     622            if (!SUP_COMP_FILENAME(szName2, szName))
    599623                rc = VINF_SUCCESS;
    600624#else
     
    603627        if (    realpath(szName, szName2) != NULL
    604628            &&  realpath(pszFilename, szName) != NULL)
    605             if (!suplibHardenedStrCmp(szName2, szName))
     629            if (!SUP_COMP_FILENAME(szName2, szName))
    606630                rc = VINF_SUCCESS;
    607631#endif
     
    645669    const char *pszName = supR3HardenedPathFilename(pszFilename);
    646670    for (unsigned iFile = 0; iFile < RT_ELEMENTS(g_aSupInstallFiles); iFile++)
    647         if (!suplibHardenedStrCmp(pszName, g_aSupInstallFiles[iFile].pszFile))
     671        if (!SUP_COMP_FILENAME(pszName, g_aSupInstallFiles[iFile].pszFile))
    648672        {
    649673            int rc = supR3HardenedVerifySameFile(iFile, pszFilename, fFatal);
     
    904928     */
    905929#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
    906     if (   RT_C_IS_ALPHA(pszSrc[0])
     930    if (   !RT_C_IS_ALPHA(pszSrc[0])
    907931        || pszSrc[1] != ':'
    908932        || !RTPATH_IS_SLASH(pszSrc[2]))
     
    14421466 *                              as we ended up with when verifying the path.
    14431467 *                              RTHCUINTPTR_MAX means NIL here.
     1468 * @param   fMaybe3rdParty      Set if the file is could be a supplied by a
     1469 *                              third party.  Different validation rules may
     1470 *                              apply to 3rd party code on some platforms.
    14441471 * @param   pErrInfo            Where to return extended error information.
    14451472 *                              Optional.
    14461473 */
    1447 DECLHIDDEN(int) supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile, PRTERRINFO pErrInfo)
     1474DECLHIDDEN(int) supR3HardenedVerifyFile(const char *pszFilename, RTHCUINTPTR hNativeFile,
     1475                                        bool fMaybe3rdParty, PRTERRINFO pErrInfo)
    14481476{
    14491477    /*
     
    14771505
    14781506    /*
    1479      * Verify the file.
     1507     * Verify the file handle against the last component, if specified.
    14801508     */
    14811509    if (hNativeFile != RTHCUINTPTR_MAX)
    1482         return supR3HardenedVerifySameFsObject(hNativeFile, &FsObjState, Info.szPath, pErrInfo);
     1510    {
     1511        rc = supR3HardenedVerifySameFsObject(hNativeFile, &FsObjState, Info.szPath, pErrInfo);
     1512        if (RT_FAILURE(rc))
     1513            return rc;
     1514    }
     1515
     1516#ifdef RT_OS_WINDOWS
     1517    /*
     1518     * The files shall be signed on windows, verify that.
     1519     */
     1520    HANDLE hVerify;
     1521    if (hNativeFile == RTHCUINTPTR_MAX)
     1522        hVerify = CreateFile(pszFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
     1523    else if (!DuplicateHandle(GetCurrentProcess(), (HANDLE)hNativeFile, GetCurrentProcess(), &hVerify,
     1524                              GENERIC_READ, false /*bInheritHandle*/, 0 /*dwOptions*/))
     1525        hVerify = INVALID_HANDLE_VALUE;
     1526    if (hVerify != INVALID_HANDLE_VALUE)
     1527    {
     1528        uint32_t fFlags = SUPHNTVI_F_REQUIRE_KERNEL_CODE_SIGNING;
     1529        if (!fMaybe3rdParty)
     1530            fFlags = SUPHNTVI_F_REQUIRE_BUILD_CERT;
     1531        const char *pszSuffix = RTPathSuffix(pszFilename);
     1532        if (   pszSuffix
     1533            &&                   pszSuffix[0]  == '.'
     1534            && (   RT_C_TO_LOWER(pszSuffix[1]) == 'r'
     1535                || RT_C_TO_LOWER(pszSuffix[1]) == 'g')
     1536            &&     RT_C_TO_LOWER(pszSuffix[2]) == 'c'
     1537            &&                   pszSuffix[3]  == '\0' )
     1538            fFlags |= SUPHNTVI_F_RC_IMAGE;
     1539# ifndef IN_SUP_R3_STATIC /* Not in VBoxCpuReport and friends. */
     1540        rc = supHardenedWinVerifyImageByHandleNoName(hVerify, fFlags, pErrInfo);
     1541# endif
     1542        CloseHandle(hVerify);
     1543    }
     1544    else
     1545        rc = RTErrInfoSetF(pErrInfo, RTErrConvertFromWin32(GetLastError()),
     1546                           "Error %u trying to open (or duplicate handle for) '%s'", GetLastError(), pszFilename);
     1547    if (RT_FAILURE(rc))
     1548        return rc;
     1549#endif
     1550
    14831551    return VINF_SUCCESS;
    14841552}
  • trunk/src/VBox/HostDrivers/Support/darwin/SUPDrv-darwin.cpp

    r51769 r51770  
    782782
    783783
     784void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     785{
     786    NOREF(pDevExt);
     787    NOREF(pSession);
     788}
     789
     790
     791void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     792{
     793    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     794}
     795
     796
     797void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     798{
     799    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     800}
     801
     802
    784803/**
    785804 * Initializes any OS specific object creator fields.
  • trunk/src/VBox/HostDrivers/Support/freebsd/SUPDrv-freebsd.c

    r49718 r51770  
    496496
    497497
     498void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     499{
     500    NOREF(pDevExt);
     501    NOREF(pSession);
     502}
     503
     504
     505void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     506{
     507    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     508}
     509
     510
     511void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     512{
     513    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     514}
     515
     516
    498517void VBOXCALL   supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession)
    499518{
  • trunk/src/VBox/HostDrivers/Support/linux/SUPDrv-linux.c

    r50008 r51770  
    809809
    810810
     811void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     812{
     813    NOREF(pDevExt);
     814    NOREF(pSession);
     815}
     816
     817
     818void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     819{
     820    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     821}
     822
     823
     824void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     825{
     826    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     827}
     828
     829
    811830/**
    812831 * Initializes any OS specific object creator fields.
  • trunk/src/VBox/HostDrivers/Support/os2/SUPDrv-os2.cpp

    r49634 r51770  
    364364
    365365
     366void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     367{
     368    NOREF(pDevExt);
     369    NOREF(pSession);
     370}
     371
     372
     373void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     374{
     375    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     376}
     377
     378
     379void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     380{
     381    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     382}
     383
     384
    366385void VBOXCALL   supdrvOSObjInitCreator(PSUPDRVOBJ pObj, PSUPDRVSESSION pSession)
    367386{
  • trunk/src/VBox/HostDrivers/Support/solaris/SUPDrv-solaris.c

    r50664 r51770  
    903903
    904904
     905void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     906{
     907    NOREF(pDevExt);
     908    NOREF(pSession);
     909}
     910
     911
     912void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     913{
     914    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     915}
     916
     917
     918void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     919{
     920    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     921}
     922
     923
    905924/**
    906925 * Initializes any OS specific object creator fields.
  • trunk/src/VBox/HostDrivers/Support/testcase/Makefile.kmk

    r43386 r51770  
    55
    66#
    7 # Copyright (C) 2006-2012 Oracle Corporation
     7# Copyright (C) 2006-2014 Oracle Corporation
    88#
    99# This file is part of VirtualBox Open Source Edition (OSE), as
  • trunk/src/VBox/HostDrivers/Support/testcase/tstNtQueryStuff.cpp

    r48952 r51770  
    55
    66/*
    7  * Copyright (C) 2006-2012 Oracle Corporation
     7 * Copyright (C) 2006-2014 Oracle Corporation
    88 *
    99 * This file is part of VirtualBox Open Source Edition (OSE), as
     
    2929*   Header Files                                                               *
    3030*******************************************************************************/
    31 #include <ntstatus.h>
    32 #define WIN32_NO_STATUS
    33 #include <Windows.h>
    34 #include <winternl.h>
    35 
    36 typedef enum
    37 {
    38     MemoryBasicInformation = 0,
    39     MemoryWorkingSetList,
    40     MemorySectionName,
    41     MemoryBasicVlmInformation
    42 } MEMORY_INFORMATION_CLASS;
    43 
    44 typedef struct
    45 {
    46     UNICODE_STRING  SectionFileName;
    47     WCHAR           NameBuffer[ANYSIZE_ARRAY];
    48 } MEMORY_SECTION_NAME;
    49 
    50 extern "C"
    51 NTSYSAPI NTSTATUS NTAPI NtQueryVirtualMemory(IN HANDLE hProcess,
    52                                              IN LPCVOID pvWhere,
    53                                              IN MEMORY_INFORMATION_CLASS MemoryInfo,
    54                                              OUT PVOID pvBuf,
    55                                              IN SIZE_T cbBuf,
    56                                              OUT PSIZE_T pcbReturned OPTIONAL);
    57 
    58 #define ProcessDebugPort            ((PROCESSINFOCLASS)7 )
    59 #define ProcessHandleCount          ((PROCESSINFOCLASS)20)
    60 #define ProcessWow64Information     ((PROCESSINFOCLASS)26)
    61 #define ProcessImageFileName        ((PROCESSINFOCLASS)27)
    62 #define ProcessDebugObjectHandle    ((PROCESSINFOCLASS)30)
    63 #define ProcessExecuteFlags         ((PROCESSINFOCLASS)34)
    64 #define ProcessImageFileNameWin32   ((PROCESSINFOCLASS)43)
    65 #define ProcessImageFileMapping     ((PROCESSINFOCLASS)44)
    66 
    67 
     31#include <iprt/nt/nt-and-windows.h>
    6832#include <iprt/test.h>
    6933#include <iprt/string.h>
     
    304268    if (NT_SUCCESS(rcNt))
    305269        RTTestIPrintf(RTTESTLVL_ALWAYS, "BasicInfo:\n"
    306                                         "    UniqueProcessId = %#x (%6d)\n"
     270                                        "    UniqueProcessId              = %#x (%6d)\n"
     271                                        "    InheritedFromUniqueProcessId = %#x (%6d)\n"
     272                                        "    ExitStatus      = %#x\n"
    307273                                        "    PebBaseAddress  = %p\n"
    308                                         "    Reserved1       = %p          ExitStatus?\n"
    309                                         "    Reserved2a      = %p          AffinityMask?\n"
    310                                         "    Reserved2b      = %p (%6d) BasePriority?\n"
    311                                         "    Reserved3       = %p (%6d) InheritedFromUniqueProcessId?\n"
     274                                        "    AffinityMask    = %#zx\n"
     275                                        "    BasePriority    = %#zx\n"
    312276                      ,
    313277                      BasicInfo.UniqueProcessId, BasicInfo.UniqueProcessId,
     278                      BasicInfo.InheritedFromUniqueProcessId, BasicInfo.InheritedFromUniqueProcessId,
     279                      BasicInfo.ExitStatus,
    314280                      BasicInfo.PebBaseAddress,
    315                       BasicInfo.Reserved1,
    316                       BasicInfo.Reserved2[0],
    317                       BasicInfo.Reserved2[1], BasicInfo.Reserved2[1],
    318                       BasicInfo.Reserved3, BasicInfo.Reserved3
     281                      BasicInfo.AffinityMask,
     282                      BasicInfo.BasePriority
    319283                      );
    320 
    321284
    322285    /* Debugger present? */
     
    435398
    436399
    437 int main()
     400int main(int argc, char **argv)
    438401{
    439402    RTEXITCODE rcExit = RTTestInitAndCreate("tstNtQueryStuff", &g_hTest);
     
    443406
    444407    g_hProcess = GetCurrentProcess();
    445 
    446     //tstQueryVirtualMemory();
     408    if (argc >= 2 && argv[1][0] != '-')
     409    {
     410        const char *pszPid = argv[1];
     411        uint32_t idPid = RTStrToInt32(pszPid);
     412
     413        uint32_t fAccess = PROCESS_QUERY_INFORMATION;
     414        if (argc >= 3)
     415            fAccess = RTStrToInt32(argv[2]);
     416
     417        g_hProcess = OpenProcess(fAccess, FALSE, idPid);
     418        if (g_hProcess == NULL)
     419        {
     420            RTTestIFailed("Error %u opening process %u (%s)\n", GetLastError(), idPid, pszPid);
     421            return RTTestSummaryAndDestroy(g_hTest);
     422        }
     423    }
     424
     425    tstQueryVirtualMemory();
    447426    tstQueryInformationProcess();
    448427
    449 
    450428    return RTTestSummaryAndDestroy(g_hTest);
    451429}
  • trunk/src/VBox/HostDrivers/Support/win/SUPDrv-win.cpp

    r51744 r51770  
    2828*   Header Files                                                               *
    2929*******************************************************************************/
     30#define IPRT_NT_MAP_TO_ZW
    3031#define LOG_GROUP LOG_GROUP_SUP_DRV
    3132#include "../SUPDrvInternal.h"
     
    3435
    3536#include <iprt/assert.h>
     37#include <iprt/avl.h>
     38#include <iprt/ctype.h>
    3639#include <iprt/initterm.h>
    3740#include <iprt/mem.h>
    3841#include <iprt/process.h>
    3942#include <iprt/power.h>
     43#include <iprt/spinlock.h>
    4044#include <iprt/string.h>
    4145#include <VBox/log.h>
     46#include <VBox/err.h>
    4247
    4348#include <iprt/asm-amd64-x86.h>
     49
     50#ifdef VBOX_WITH_HARDENING
     51# include "SUPHardenedVerify-win.h"
     52#endif
    4453
    4554
     
    6675#define DEVICE_NAME_DOS_USR     L"\\DosDevices\\VBoxDrvU"
    6776
     77#ifdef VBOX_WITH_HARDENING
     78/** Win32 device name for hardened stub access. */
     79# define DEVICE_NAME_STUB       "\\\\.\\VBoxDrvStub"
     80/** NT device name for hardened stub access. */
     81# define DEVICE_NAME_NT_STUB    L"\\Device\\VBoxDrvStub"
     82///** Win Symlink name for hardened stub access. */
     83//# define DEVICE_NAME_DOS_STUB   L"\\DosDevices\\VBoxDrvStub"
     84
     85
     86/** Macro for checking for deflecting calls to the stub device. */
     87# define VBOXDRV_COMPLETE_IRP_AND_RETURN_IF_STUB_DEV(a_pDevObj, a_pIrp) \
     88    do { if ((a_pDevObj) == g_pDevObjStub) supdrvNtCompleteRequest(STATUS_ACCESS_DENIED, a_pIrp); } while (0)
     89#else
     90# define VBOXDRV_COMPLETE_IRP_AND_RETURN_IF_STUB_DEV(a_pDevObj, a_pIrp) do {} while (0)
     91#endif
     92
    6893/** Enables the fast I/O control code path. */
    6994#define VBOXDRV_WITH_FAST_IO
     
    7398*   Structures and Typedefs                                                    *
    7499*******************************************************************************/
    75 #if 0 //def RT_ARCH_AMD64
    76 typedef struct SUPDRVEXECMEM
    77 {
    78     PMDL pMdl;
    79     void *pvMapping;
    80     void *pvAllocation;
    81 } SUPDRVEXECMEM, *PSUPDRVEXECMEM;
    82 #endif
    83 
    84100/**
    85101 * Device extension used by VBoxDrvU.
     
    103119     ? (PSUPDRVDEVEXT)pDevObj->DeviceExtension \
    104120     : ((PSUPDRVDEVEXTUSR)pDevObj->DeviceExtension)->pMainDrvExt )
     121
     122#ifdef VBOX_WITH_HARDENING
     123
     124/**
     125 * Device extension used by VBoxDrvS.
     126 */
     127typedef struct SUPDRVDEVEXTSTUB
     128{
     129    /** Common header. */
     130    SUPDRVDEVEXTUSR     Common;
     131} SUPDRVDEVEXTSTUB;
     132/** Pointer to the VBoxDrvS device extension. */
     133typedef SUPDRVDEVEXTSTUB *PSUPDRVDEVEXTSTUB;
     134/** Value of SUPDRVDEVEXTSTUB::Common.u32Cookie. */
     135#define SUPDRVDEVEXTSTUB_COOKIE      UINT32_C(0x90abcdef)
     136
     137
     138/**
     139 * The kind of process we're protecting.
     140 */
     141typedef enum SUPDRVNTPROTECTKIND
     142{
     143    kSupDrvNtProtectKind_Invalid = 0,
     144
     145    /** Stub process protection while performing process verification.
     146     * Next: StubSpawning (or free)  */
     147    kSupDrvNtProtectKind_StubUnverified,
     148    /** Stub process protection before it creates the VM process.
     149     * Next: StubParent, StubDead. */
     150    kSupDrvNtProtectKind_StubSpawning,
     151    /** Stub process protection while having a VM process as child.
     152     * Next: StubDead  */
     153    kSupDrvNtProtectKind_StubParent,
     154    /** Dead stub process. */
     155    kSupDrvNtProtectKind_StubDead,
     156
     157    /** Potential VM process.
     158     * Next: VmProcessConfirmed, VmProcessDead. */
     159    kSupDrvNtProtectKind_VmProcessUnconfirmed,
     160    /** Confirmed VM process.
     161     * Next: VmProcessDead. */
     162    kSupDrvNtProtectKind_VmProcessConfirmed,
     163    /** Dead VM process. */
     164    kSupDrvNtProtectKind_VmProcessDead,
     165
     166    /** End of valid protection kinds. */
     167    kSupDrvNtProtectKind_End
     168} SUPDRVNTPROTECTKIND;
     169
     170/**
     171 * A NT process protection structure.
     172 */
     173typedef struct SUPDRVNTPROTECT
     174{
     175    /** The AVL node core structure.  The process ID is the pid. */
     176    AVLPVNODECORE       AvlCore;
     177    /** Magic value (SUPDRVNTPROTECT_MAGIC). */
     178    uint32_t volatile   u32Magic;
     179    /** Reference counter. */
     180    uint32_t volatile   cRefs;
     181    /** The kind of process we're protecting. */
     182    SUPDRVNTPROTECTKIND volatile enmProcessKind;
     183    /** Vista, 7 & 8: Hack to allow more rights to the handle returned by
     184     *  NtCreateUserProcess. Only applicable to VmProcessUnconfirmed. */
     185    bool                fFirstProcessCreateHandle : 1;
     186    /** Vista, 7 & 8: Hack to allow more rights to the handle returned by
     187     *  NtCreateUserProcess. Only applicable to VmProcessUnconfirmed. */
     188    bool                fFirstThreadCreateHandle : 1;
     189    /** 8.1: Hack to allow more rights to the handle returned by
     190     *  NtCreateUserProcess. Only applicable to VmProcessUnconfirmed. */
     191    bool                fCsrssFirstProcessCreateHandle : 1;
     192    /** Vista, 7 & 8: Hack to allow more rights to the handle duplicated by CSR
     193     *  during process creation. Only applicable to VmProcessUnconfirmed. */
     194    bool                fCsrssFirstProcessDuplicateHandle : 1;
     195    /** 7,: Hack to allow the supid themes service duplicate handle privileges to
     196     *  our process. */
     197    bool                fThemesFirstProcessCreateHandle : 1;
     198
     199    /** The parent PID for VM processes, otherwise NULL. */
     200    HANDLE              hParentPid;
     201    /** The PID of the CSRSS process associated with this process. */
     202    HANDLE              hCsrssPid;
     203    /** Pointer to the CSRSS process structure (referenced). */
     204    PEPROCESS           pCsrssProcess;
     205    /** State dependent data. */
     206    union
     207    {
     208        /** A stub process in the StubParent state will keep a reference to a child
     209         * while it's in the VmProcessUnconfirmed state so that it can be cleaned up
     210         * correctly if things doesn't work out. */
     211        struct SUPDRVNTPROTECT *pChild;
     212        /** A process in the VmProcessUnconfirmed state will keep a weak
     213         * reference to the parent's protection structure so it can clean up the pChild
     214         * refernece the parent has to it. */
     215        struct SUPDRVNTPROTECT *pParent;
     216    } u;
     217} SUPDRVNTPROTECT;
     218/** Pointer to a NT process protection record. */
     219typedef SUPDRVNTPROTECT *PSUPDRVNTPROTECT;
     220/** The SUPDRVNTPROTECT::u32Magic value (Robert A. Heinlein). */
     221# define SUPDRVNTPROTECT_MAGIC      UINT32_C(0x19070707)
     222/** The SUPDRVNTPROTECT::u32Magic value of a dead structure. */
     223# define SUPDRVNTPROTECT_MAGIC_DEAD UINT32_C(0x19880508)
     224
     225/** Pointer to ObRegisterCallbacks. */
     226typedef NTSTATUS (NTAPI *PFNOBREGISTERCALLBACKS)(POB_CALLBACK_REGISTRATION, PVOID *);
     227/** Pointer to ObUnregisterCallbacks. */
     228typedef VOID     (NTAPI *PFNOBUNREGISTERCALLBACKS)(PVOID);
     229/** Pointer to PsSetCreateProcessNotifyRoutineEx. */
     230typedef NTSTATUS (NTAPI *PFNPSSETCREATEPROCESSNOTIFYROUTINEEX)(PCREATE_PROCESS_NOTIFY_ROUTINE_EX, BOOLEAN);
     231/** Pointer to PsReferenceProcessFilePointer. */
     232typedef NTSTATUS (NTAPI *PFNPSREFERENCEPROCESSFILEPOINTER)(PEPROCESS, PFILE_OBJECT *);
     233/** Pointer to PsIsProtectedProcessLight. */
     234typedef BOOLEAN  (NTAPI *PFNPSISPROTECTEDPROCESSLIGHT)(PEPROCESS);
     235
     236#endif /* VBOX_WITH_HARDENINIG */
    105237
    106238
     
    123255static NTSTATUS _stdcall   VBoxDrvNtNotSupportedStub(PDEVICE_OBJECT pDevObj, PIRP pIrp);
    124256static NTSTATUS            VBoxDrvNtErr2NtStatus(int rc);
     257#ifdef VBOX_WITH_HARDENING
     258static NTSTATUS             supdrvNtProtectInit(void);
     259static void                 supdrvNtProtectTerm(void);
     260static int                  supdrvNtProtectCreate(PSUPDRVNTPROTECT *ppNtProtect, HANDLE hPid,
     261                                                  SUPDRVNTPROTECTKIND enmProcessKind, bool fLink);
     262static void                 supdrvNtProtectRelease(PSUPDRVNTPROTECT pNtProtect);
     263static PSUPDRVNTPROTECT     supdrvNtProtectLookup(HANDLE hPid);
     264static int                  supdrvNtProtectFindAssociatedCsrss(PSUPDRVNTPROTECT pNtProtect);
     265static int                  supdrvNtProtectVerifyProcess(PSUPDRVNTPROTECT pNtProtect);
     266
     267static bool                 supdrvNtIsDebuggerAttached(void);
     268#endif
    125269
    126270
     
    175319#endif /* VBOXDRV_WITH_FAST_IO */
    176320
     321#ifdef VBOX_WITH_HARDENING
     322/** Pointer to the stub device instance. */
     323static PDEVICE_OBJECT               g_pDevObjStub = NULL;
     324/** Spinlock protecting g_NtProtectTree as well as the releasing of protection
     325 *  structures. */
     326static RTSPINLOCK                   g_hNtProtectLock = NIL_RTSPINLOCK;
     327/** AVL tree of SUPDRVNTPROTECT structures. */
     328static AVLPVTREE                    g_NtProtectTree  = NULL;
     329/** Cookie returned by ObRegisterCallbacks for the callbacks. */
     330static PVOID                        g_pvObCallbacksCookie = NULL;
     331/** Combined windows NT version number.  See SUP_MAKE_NT_VER_COMBINED. */
     332uint32_t                            g_uNtVerCombined = 0;
     333/** Pointer to ObRegisterCallbacks if available.. */
     334static PFNOBREGISTERCALLBACKS       g_pfnObRegisterCallbacks = NULL;
     335/** Pointer to ObUnregisterCallbacks if available.. */
     336static PFNOBUNREGISTERCALLBACKS     g_pfnObUnRegisterCallbacks = NULL;
     337/** Pointer to PsSetCreateProcessNotifyRoutineEx if available.. */
     338static PFNPSSETCREATEPROCESSNOTIFYROUTINEEX g_pfnPsSetCreateProcessNotifyRoutineEx = NULL;
     339/** Pointer to PsReferenceProcessFilePointer if available. */
     340static PFNPSREFERENCEPROCESSFILEPOINTER g_pfnPsReferenceProcessFilePointer = NULL;
     341/** Pointer to PsIsProtectedProcessLight. */
     342static PFNPSISPROTECTEDPROCESSLIGHT g_pfnPsIsProtectedProcessLight = NULL;
     343
     344# ifdef RT_ARCH_AMD64
     345extern "C" {
     346/** Pointer to KiServiceLinkage (used to fake missing ZwQueryVirtualMemory on
     347 *  XP64 / W2K3-64). */
     348PFNRT                               g_pfnKiServiceLinkage  = NULL;
     349/** Pointer to KiServiceInternal (used to fake missing ZwQueryVirtualMemory on
     350 *  XP64 / W2K3-64) */
     351PFNRT                               g_pfnKiServiceInternal = NULL;
     352}
     353# endif
     354#endif
     355
    177356
    178357/**
     
    192371    if (NT_SUCCESS(rcNt))
    193372    {
    194         UNICODE_STRING DosName;
    195         RtlInitUnicodeString(&DosName, DEVICE_NAME_DOS_SYS);
    196         rcNt = IoCreateSymbolicLink(&DosName, &DevName);
     373        UNICODE_STRING DosNameSys;
     374        RtlInitUnicodeString(&DosNameSys, DEVICE_NAME_DOS_SYS);
     375        rcNt = IoCreateSymbolicLink(&DosNameSys, &DevName);
    197376        if (NT_SUCCESS(rcNt))
    198377        {
     
    204383            if (NT_SUCCESS(rcNt))
    205384            {
    206                 UNICODE_STRING DosName;
    207                 RtlInitUnicodeString(&DosName, DEVICE_NAME_DOS_USR);
    208                 rcNt = IoCreateSymbolicLink(&DosName, &DevName);
     385                UNICODE_STRING DosNameUsr;
     386                RtlInitUnicodeString(&DosNameUsr, DEVICE_NAME_DOS_USR);
     387                rcNt = IoCreateSymbolicLink(&DosNameUsr, &DevName);
    209388                if (NT_SUCCESS(rcNt))
    210389                {
     
    213392                    pDevExtUsr->u32Cookie   = SUPDRVDEVEXTUSR_COOKIE;
    214393
    215                     /* Done. */
    216                     return rcNt;
     394#ifdef VBOX_WITH_HARDENING
     395                    /*
     396                     * Hardened stub device.
     397                     */
     398                    RtlInitUnicodeString(&DevName, DEVICE_NAME_NT_STUB);
     399                    rcNt = IoCreateDevice(pDrvObj, sizeof(SUPDRVDEVEXTSTUB), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &g_pDevObjStub);
     400                    if (NT_SUCCESS(rcNt))
     401                    {
     402                        //UNICODE_STRING DosNameStub;
     403                        //RtlInitUnicodeString(&DosNameStub, DEVICE_NAME_DOS_STUB);
     404                        //rcNt = IoCreateSymbolicLink(&DosNameStub, &DevName);
     405                        if (NT_SUCCESS(rcNt))
     406                        {
     407                            PSUPDRVDEVEXTSTUB pDevExtStub = (PSUPDRVDEVEXTSTUB)g_pDevObjStub->DeviceExtension;
     408                            pDevExtStub->Common.pMainDrvExt = (PSUPDRVDEVEXT)g_pDevObjSys->DeviceExtension;
     409                            pDevExtStub->Common.u32Cookie   = SUPDRVDEVEXTSTUB_COOKIE;
     410#endif
     411
     412                            /* Done. */
     413                            return rcNt;
     414#ifdef VBOX_WITH_HARDENING
     415                        }
     416
     417                        /* Bail out. */
     418                        IoDeleteDevice(g_pDevObjStub);
     419                        g_pDevObjUsr = NULL;
     420                    }
     421                    IoDeleteSymbolicLink(&DosNameUsr);
     422#endif
    217423                }
    218 
    219                 /* Bail out. */
    220424                IoDeleteDevice(g_pDevObjUsr);
    221425                g_pDevObjUsr = NULL;
    222426            }
    223             IoDeleteSymbolicLink(&DosName);
     427            IoDeleteSymbolicLink(&DosNameSys);
    224428        }
    225429        IoDeleteDevice(g_pDevObjSys);
     
    241445    rcNt = IoDeleteSymbolicLink(&DosName);
    242446
    243     PSUPDRVDEVEXTUSR pDevExtUsr = (PSUPDRVDEVEXTUSR)g_pDevObjUsr->DeviceExtension;
    244     pDevExtUsr->pMainDrvExt = NULL;
    245 
     447#ifdef VBOX_WITH_HARDENING
     448    //RtlInitUnicodeString(&DosName, DEVICE_NAME_DOS_STUB);
     449    //rcNt = IoDeleteSymbolicLink(&DosName);
     450#endif
     451
     452    if (g_pDevObjUsr)
     453    {
     454        PSUPDRVDEVEXTUSR pDevExtUsr = (PSUPDRVDEVEXTUSR)g_pDevObjUsr->DeviceExtension;
     455        pDevExtUsr->pMainDrvExt = NULL;
     456    }
     457#ifdef VBOX_WITH_HARDENING
     458    if (g_pDevObjStub)
     459    {
     460        PSUPDRVDEVEXTSTUB pDevExtStub = (PSUPDRVDEVEXTSTUB)g_pDevObjStub->DeviceExtension;
     461        pDevExtStub->Common.pMainDrvExt = NULL;
     462    }
     463#endif
     464
     465#ifdef VBOX_WITH_HARDENING
     466    IoDeleteDevice(g_pDevObjStub);
     467    g_pDevObjStub = NULL;
     468#endif
    246469    IoDeleteDevice(g_pDevObjUsr);
    247470    g_pDevObjUsr = NULL;
     
    273496
    274497    /*
    275      * Create device.
    276      * (That means creating a device object and a symbolic link so the DOS
    277      * subsystems (OS/2, win32, ++) can access the device.)
     498     * Initialize the runtime (IPRT).
    278499     */
    279     NTSTATUS rcNt = vboxdrvNtCreateDevices(pDrvObj);
    280     if (NT_SUCCESS(rcNt))
    281     {
    282         int vrc = RTR0Init(0);
    283         if (RT_SUCCESS(vrc))
    284         {
    285             Log(("VBoxDrv::DriverEntry\n"));
    286 
     500    NTSTATUS rcNt;
     501    int vrc = RTR0Init(0);
     502    if (RT_SUCCESS(vrc))
     503    {
     504        Log(("VBoxDrv::DriverEntry\n"));
     505
     506#ifdef VBOX_WITH_HARDENING
     507        /*
     508         * Initialize process protection.
     509         */
     510        rcNt = supdrvNtProtectInit();
     511        if (NT_SUCCESS(rcNt))
     512#endif
     513        {
    287514            /*
    288              * Initialize the device extension.
     515             * Create device.
     516             * (That means creating a device object and a symbolic link so the DOS
     517             * subsystems (OS/2, win32, ++) can access the device.)
    289518             */
    290             PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)g_pDevObjSys->DeviceExtension;
    291             memset(pDevExt, 0, sizeof(*pDevExt));
    292 
    293             vrc = supdrvInitDevExt(pDevExt, sizeof(SUPDRVSESSION));
    294             if (!vrc)
     519            rcNt = vboxdrvNtCreateDevices(pDrvObj);
     520            if (NT_SUCCESS(rcNt))
    295521            {
    296522                /*
    297                  * Setup the driver entry points in pDrvObj.
     523                 * Initialize the device extension.
    298524                 */
    299                 pDrvObj->DriverUnload                                   = VBoxDrvNtUnload;
    300                 pDrvObj->MajorFunction[IRP_MJ_CREATE]                   = VBoxDrvNtCreate;
    301                 pDrvObj->MajorFunction[IRP_MJ_CLEANUP]                  = VBoxDrvNtCleanup;
    302                 pDrvObj->MajorFunction[IRP_MJ_CLOSE]                    = VBoxDrvNtClose;
    303                 pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL]           = VBoxDrvNtDeviceControl;
    304                 pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL]  = VBoxDrvNtInternalDeviceControl;
    305                 pDrvObj->MajorFunction[IRP_MJ_READ]                     = VBoxDrvNtNotSupportedStub;
    306                 pDrvObj->MajorFunction[IRP_MJ_WRITE]                    = VBoxDrvNtNotSupportedStub;
    307 
    308                 /* more? */
     525                PSUPDRVDEVEXT pDevExt = (PSUPDRVDEVEXT)g_pDevObjSys->DeviceExtension;
     526                memset(pDevExt, 0, sizeof(*pDevExt));
     527
     528                vrc = supdrvInitDevExt(pDevExt, sizeof(SUPDRVSESSION));
     529                if (!vrc)
     530                {
     531                    /*
     532                     * Setup the driver entry points in pDrvObj.
     533                     */
     534                    pDrvObj->DriverUnload                                   = VBoxDrvNtUnload;
     535                    pDrvObj->MajorFunction[IRP_MJ_CREATE]                   = VBoxDrvNtCreate;
     536                    pDrvObj->MajorFunction[IRP_MJ_CLEANUP]                  = VBoxDrvNtCleanup;
     537                    pDrvObj->MajorFunction[IRP_MJ_CLOSE]                    = VBoxDrvNtClose;
     538                    pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL]           = VBoxDrvNtDeviceControl;
     539                    pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL]  = VBoxDrvNtInternalDeviceControl;
     540                    pDrvObj->MajorFunction[IRP_MJ_READ]                     = VBoxDrvNtNotSupportedStub;
     541                    pDrvObj->MajorFunction[IRP_MJ_WRITE]                    = VBoxDrvNtNotSupportedStub;
    309542
    310543#ifdef VBOXDRV_WITH_FAST_IO
    311                 /* Fast I/O to speed up guest execution roundtrips. */
    312                 pDrvObj->FastIoDispatch = (PFAST_IO_DISPATCH)&g_VBoxDrvFastIoDispatch;
     544                    /* Fast I/O to speed up guest execution roundtrips. */
     545                    pDrvObj->FastIoDispatch = (PFAST_IO_DISPATCH)&g_VBoxDrvFastIoDispatch;
    313546#endif
    314547
    315                 /* Register ourselves for power state changes. */
    316                 UNICODE_STRING      CallbackName;
    317                 OBJECT_ATTRIBUTES   Attr;
    318 
    319                 RtlInitUnicodeString(&CallbackName, L"\\Callback\\PowerState");
    320                 InitializeObjectAttributes(&Attr, &CallbackName, OBJ_CASE_INSENSITIVE, NULL, NULL);
    321 
    322                 rcNt = ExCreateCallback(&pDevExt->pObjPowerCallback, &Attr, TRUE, TRUE);
    323                 if (rcNt == STATUS_SUCCESS)
    324                     pDevExt->hPowerCallback = ExRegisterCallback(pDevExt->pObjPowerCallback, VBoxPowerDispatchCallback,
    325                                                                  g_pDevObjSys);
    326 
    327                 Log(("VBoxDrv::DriverEntry returning STATUS_SUCCESS\n"));
    328                 return STATUS_SUCCESS;
    329             }
    330 
    331             Log(("supdrvInitDevExit failed with vrc=%d!\n", vrc));
    332             rcNt = VBoxDrvNtErr2NtStatus(vrc);
    333 
    334             RTR0Term();
    335         }
    336         else
    337         {
    338             Log(("RTR0Init failed with vrc=%d!\n", vrc));
    339             rcNt = VBoxDrvNtErr2NtStatus(vrc);
    340         }
    341 
    342         vboxdrvNtDestroyDevices();
     548                    /*
     549                     * Register ourselves for power state changes.  We don't
     550                     * currently care if this fails.
     551                     */
     552                    UNICODE_STRING      CallbackName;
     553                    RtlInitUnicodeString(&CallbackName, L"\\Callback\\PowerState");
     554
     555                    OBJECT_ATTRIBUTES   Attr;
     556                    InitializeObjectAttributes(&Attr, &CallbackName, OBJ_CASE_INSENSITIVE, NULL, NULL);
     557
     558                    rcNt = ExCreateCallback(&pDevExt->pObjPowerCallback, &Attr, TRUE, TRUE);
     559                    if (rcNt == STATUS_SUCCESS)
     560                        pDevExt->hPowerCallback = ExRegisterCallback(pDevExt->pObjPowerCallback,
     561                                                                     VBoxPowerDispatchCallback,
     562                                                                     g_pDevObjSys);
     563
     564                    /*
     565                     * Done! Returning success!
     566                     */
     567                    Log(("VBoxDrv::DriverEntry returning STATUS_SUCCESS\n"));
     568                    return STATUS_SUCCESS;
     569                }
     570
     571                Log(("supdrvInitDevExit failed with vrc=%d!\n", vrc));
     572                rcNt = VBoxDrvNtErr2NtStatus(vrc);
     573
     574                vboxdrvNtDestroyDevices();
     575            }
     576#ifdef VBOX_WITH_HARDENING
     577            supdrvNtProtectTerm();
     578#endif
     579        }
     580        RTR0Term();
     581    }
     582    else
     583    {
     584        Log(("RTR0Init failed with vrc=%d!\n", vrc));
     585        rcNt = VBoxDrvNtErr2NtStatus(vrc);
    343586    }
    344587    if (NT_SUCCESS(rcNt))
     
    369612     */
    370613    supdrvDeleteDevExt(pDevExt);
     614#ifdef VBOX_WITH_HARDENING
     615    supdrvNtProtectTerm();
     616#endif
    371617    RTR0Term();
    372618    vboxdrvNtDestroyDevices();
     
    377623
    378624/**
     625 * For simplifying request completion into a simple return statement, extended
     626 * version.
     627 *
     628 * @returns rcNt
     629 * @param   rcNt                The status code.
     630 * @param   uInfo               Extra info value.
     631 * @param   pIrp                The IRP.
     632 */
     633DECLINLINE(NTSTATUS) supdrvNtCompleteRequestEx(NTSTATUS rcNt, ULONG_PTR uInfo, PIRP pIrp)
     634{
     635    pIrp->IoStatus.Status       = rcNt;
     636    pIrp->IoStatus.Information  = uInfo;
     637    IoCompleteRequest(pIrp, IO_NO_INCREMENT);
     638    return rcNt;
     639}
     640
     641
     642/**
     643 * For simplifying request completion into a simple return statement.
     644 *
     645 * @returns rcNt
     646 * @param   rcNt                The status code.
     647 * @param   pIrp                The IRP.
     648 */
     649DECLINLINE(NTSTATUS) supdrvNtCompleteRequest(NTSTATUS rcNt, PIRP pIrp)
     650{
     651    return supdrvNtCompleteRequestEx(rcNt, 0 /*uInfo*/, pIrp);
     652}
     653
     654
     655/**
    379656 * Create (i.e. Open) file entry point.
    380657 *
     
    385662{
    386663    Log(("VBoxDrvNtCreate: RequestorMode=%d\n", pIrp->RequestorMode));
    387     const bool          fUnrestricted = pDevObj == g_pDevObjSys;
    388     PIO_STACK_LOCATION  pStack = IoGetCurrentIrpStackLocation(pIrp);
     664    PIO_STACK_LOCATION  pStack   = IoGetCurrentIrpStackLocation(pIrp);
    389665    PFILE_OBJECT        pFileObj = pStack->FileObject;
    390     PSUPDRVDEVEXT       pDevExt = SUPDRVNT_GET_DEVEXT(pDevObj);
     666    PSUPDRVDEVEXT       pDevExt  = SUPDRVNT_GET_DEVEXT(pDevObj);
    391667
    392668    /*
     
    395671     */
    396672    if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE)
    397     {
    398         pIrp->IoStatus.Status       = STATUS_NOT_A_DIRECTORY;
    399         pIrp->IoStatus.Information  = 0;
    400         IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    401         return STATUS_NOT_A_DIRECTORY;
    402     }
     673        return supdrvNtCompleteRequest(STATUS_NOT_A_DIRECTORY, pIrp);
    403674
    404675    /*
    405676     * Don't create a session for kernel clients, they'll close the handle
    406677     * immediately and work with the file object via
    407      * VBoxDrvNtInternalDeviceControl.  The first request will there be one
    408      * to create a session.
     678     * VBoxDrvNtInternalDeviceControl.  The first request will be one to
     679     * create a session.
    409680     */
    410681    NTSTATUS rcNt;
    411682    if (pIrp->RequestorMode == KernelMode)
    412         rcNt = STATUS_SUCCESS;
     683    {
     684        if (pDevObj == g_pDevObjSys)
     685            return supdrvNtCompleteRequestEx(STATUS_SUCCESS, FILE_OPENED, pIrp);
     686
     687        rcNt = STATUS_ACCESS_DENIED;
     688    }
    413689    else
    414690    {
     691#if defined(VBOX_WITH_HARDENING) && !defined(VBOX_WITHOUT_DEBUGGER_CHECKS)
    415692        /*
    416          * Call common code for the rest.
     693         * Make sure no debuggers are attached to non-user processes.
    417694         */
    418         pFileObj->FsContext = NULL;
    419         PSUPDRVSESSION pSession;
    420         int rc = supdrvCreateSession(pDevExt, true /*fUser*/, fUnrestricted, &pSession);
    421         if (!rc)
    422             pFileObj->FsContext = pSession;
    423         rcNt = pIrp->IoStatus.Status = VBoxDrvNtErr2NtStatus(rc);
    424     }
    425 
    426     pIrp->IoStatus.Information  = 0;
    427     IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    428 
    429     return rcNt;
     695        if (   pDevObj != g_pDevObjUsr
     696            && supdrvNtIsDebuggerAttached())
     697        {
     698            LogRel(("vboxdrv: Process %p is being debugged, access to vboxdrv / vboxdrvu declined.\n",
     699                    PsGetProcessId(PsGetCurrentProcess())));
     700            rcNt = STATUS_TRUST_FAILURE;
     701        }
     702        else
     703#endif
     704        {
     705            int rc = VINF_SUCCESS;
     706
     707#ifdef VBOX_WITH_HARDENING
     708            /*
     709             * Access to the stub device is only granted to processes which
     710             * passes verification.
     711             *
     712             * Note! The stub device has no need for a SUPDRVSESSION structure,
     713             *       so the it uses the SUPDRVNTPROTECT directly instead.
     714             */
     715            if (pDevObj == g_pDevObjStub)
     716            {
     717                PSUPDRVNTPROTECT pNtProtect = NULL;
     718                rc = supdrvNtProtectCreate(&pNtProtect, PsGetProcessId(PsGetCurrentProcess()),
     719                                           kSupDrvNtProtectKind_StubUnverified, true /*fLink*/);
     720                if (RT_SUCCESS(rc))
     721                {
     722                    rc = supdrvNtProtectFindAssociatedCsrss(pNtProtect);
     723                    if (RT_SUCCESS(rc))
     724                        rc = supdrvNtProtectVerifyProcess(pNtProtect);
     725                    if (RT_SUCCESS(rc))
     726                    {
     727                        pFileObj->FsContext = pNtProtect; /* Keeps reference. */
     728                        return supdrvNtCompleteRequestEx(STATUS_SUCCESS, FILE_OPENED, pIrp);
     729                    }
     730
     731                    supdrvNtProtectRelease(pNtProtect);
     732                }
     733                LogRel(("vboxdrv: Declined %p access to VBoxDrvStub: rc=%d\n", PsGetProcessId(PsGetCurrentProcess()), rc));
     734            }
     735            /*
     736             * Unrestricted access is only granted to a process in the
     737             * VmProcessUnconfirmed state that checks out correctly and is
     738             * allowed to transition to VmProcessConfirmed.  Again, only one
     739             * session per process.
     740             */
     741            else if (pDevObj != g_pDevObjUsr)
     742            {
     743                PSUPDRVNTPROTECT pNtProtect = supdrvNtProtectLookup(PsGetProcessId(PsGetCurrentProcess()));
     744                if (pNtProtect)
     745                {
     746                    if (pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed)
     747                    {
     748                        rc = supdrvNtProtectVerifyProcess(pNtProtect);
     749                        if (RT_SUCCESS(rc))
     750                        {
     751                            /* Create a session. */
     752                            PSUPDRVSESSION pSession;
     753                            rc = supdrvCreateSession(pDevExt, true /*fUser*/, pDevObj == g_pDevObjSys /*fUnrestricted*/,
     754                                                     &pSession);
     755                            if (RT_SUCCESS(rc))
     756                            {
     757                                rc = supdrvSessionHashTabInsert(pDevExt, pSession, (PSUPDRVSESSION *)&pFileObj->FsContext, NULL);
     758                                supdrvSessionRelease(pSession);
     759                                if (RT_SUCCESS(rc))
     760                                {
     761                                    pSession->pNtProtect = pNtProtect; /* Keeps reference. */
     762                                    return supdrvNtCompleteRequestEx(STATUS_SUCCESS, FILE_OPENED, pIrp);
     763                                }
     764                            }
     765
     766                            /* No second attempt. */
     767                            RTSpinlockAcquire(g_hNtProtectLock);
     768                            if (pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessConfirmed)
     769                                pNtProtect->enmProcessKind = kSupDrvNtProtectKind_VmProcessDead;
     770                            RTSpinlockRelease(g_hNtProtectLock);
     771
     772                            LogRel(("vboxdrv: supdrvCreateSession failed for process %p: rc=%d.\n",
     773                                    PsGetProcessId(PsGetCurrentProcess()), rc));
     774                        }
     775                        else
     776                            LogRel(("vboxdrv: Process %p failed process verification: rc=%d.\n",
     777                                    PsGetProcessId(PsGetCurrentProcess()), rc));
     778                    }
     779                    else
     780                    {
     781                        LogRel(("vboxdrv: %p is not a budding VM process (enmProcessKind=%d).\n",
     782                                PsGetProcessId(PsGetCurrentProcess()), pNtProtect->enmProcessKind));
     783                        rc = VERR_ACCESS_DENIED;
     784                    }
     785                    supdrvNtProtectRelease(pNtProtect);
     786                }
     787                else
     788                {
     789                    LogRel(("vboxdrv: %p is not a budding VM process.\n", PsGetProcessId(PsGetCurrentProcess())));
     790                    rc = VERR_ACCESS_DENIED;
     791                }
     792            }
     793            /*
     794             * Call common code to create an unprivileged session.
     795             */
     796            else
     797            {
     798                PSUPDRVSESSION pSession;
     799                rc = supdrvCreateSession(pDevExt, true /*fUser*/, false /*fUnrestricted*/, &pSession);
     800                if (RT_SUCCESS(rc))
     801                {
     802                    rc = supdrvSessionHashTabInsert(pDevExt, pSession, (PSUPDRVSESSION *)&pFileObj->FsContext, NULL);
     803                    supdrvSessionRelease(pSession);
     804                    if (RT_SUCCESS(rc))
     805                    {
     806                        pFileObj->FsContext  = pSession; /* Keeps reference. No race. */
     807                        pSession->pNtProtect = NULL;
     808                        return supdrvNtCompleteRequestEx(STATUS_SUCCESS, FILE_OPENED, pIrp);
     809                    }
     810                }
     811            }
     812
     813#else  /* !VBOX_WITH_HARDENING */
     814            /*
     815             * Call common code to create a session.
     816             */
     817            pFileObj->FsContext = NULL;
     818            PSUPDRVSESSION pSession;
     819            rc = supdrvCreateSession(pDevExt, true /*fUser*/, pDevObj == g_pDevObjSys /*fUnrestricted*/, &pSession);
     820            if (RT_SUCCESS(rc))
     821            {
     822                rc = supdrvSessionHashTabInsert(pDevExt, pSession, (PSUPDRVSESSION *)&pFileObj->FsContext, NULL);
     823                supdrvSessionRelease(pSession);
     824                if (RT_SUCCESS(rc))
     825                    return supdrvNtCompleteRequestEx(STATUS_SUCCESS, FILE_OPENED, pIrp);
     826
     827            }
     828#endif /* !VBOX_WITH_HARDENING */
     829
     830            /* bail out */
     831            rcNt = VBoxDrvNtErr2NtStatus(rc);
     832        }
     833    }
     834
     835    Assert(!NT_SUCCESS(rcNt));
     836    pFileObj->FsContext = NULL;
     837    return supdrvNtCompleteRequest(rcNt, pIrp); /* Note. the IoStatus is completely ignored on error. */
    430838}
    431839
     
    442850    PIO_STACK_LOCATION  pStack   = IoGetCurrentIrpStackLocation(pIrp);
    443851    PFILE_OBJECT        pFileObj = pStack->FileObject;
    444     PSUPDRVSESSION      pSession = (PSUPDRVSESSION)pFileObj->FsContext;
    445 
    446     Log(("VBoxDrvNtCleanup: pDevExt=%p pFileObj=%p pSession=%p\n", pDevExt, pFileObj, pSession));
    447     if (pSession)
    448     {
    449         supdrvSessionRelease(pSession);
    450         pFileObj->FsContext = NULL;
    451     }
    452 
    453     pIrp->IoStatus.Information = 0;
    454     pIrp->IoStatus.Status = STATUS_SUCCESS;
    455     IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    456 
    457     return STATUS_SUCCESS;
     852
     853#ifdef VBOX_WITH_HARDENING
     854    if (pDevObj == g_pDevObjStub)
     855    {
     856        PSUPDRVNTPROTECT pNtProtect = (PSUPDRVNTPROTECT)pFileObj->FsContext;
     857        Log(("VBoxDrvNtCleanup: pDevExt=%p pFileObj=%p pNtProtect=%p\n", pDevExt, pFileObj, pNtProtect));
     858        if (pNtProtect)
     859        {
     860            supdrvNtProtectRelease(pNtProtect);
     861            pFileObj->FsContext = NULL;
     862        }
     863    }
     864    else
     865#endif
     866    {
     867        PSUPDRVSESSION pSession = supdrvSessionHashTabLookup(pDevExt, RTProcSelf(), RTR0ProcHandleSelf(),
     868                                                             (PSUPDRVSESSION *)&pFileObj->FsContext);
     869        Log(("VBoxDrvNtCleanup: pDevExt=%p pFileObj=%p pSession=%p\n", pDevExt, pFileObj, pSession));
     870        if (pSession)
     871        {
     872            supdrvSessionHashTabRemove(pDevExt, pSession, NULL);
     873            supdrvSessionRelease(pSession); /* Drops the reference from supdrvSessionHashTabLookup. */
     874        }
     875    }
     876
     877    return supdrvNtCompleteRequest(STATUS_SUCCESS, pIrp);
    458878}
    459879
     
    470890    PIO_STACK_LOCATION  pStack   = IoGetCurrentIrpStackLocation(pIrp);
    471891    PFILE_OBJECT        pFileObj = pStack->FileObject;
    472     PSUPDRVSESSION      pSession = (PSUPDRVSESSION)pFileObj->FsContext;
    473 
    474     Log(("VBoxDrvNtClose: pDevExt=%p pFileObj=%p pSession=%p\n", pDevExt, pFileObj, pSession));
    475     if (pSession)
    476     {
    477         supdrvSessionRelease(pSession);
    478         pFileObj->FsContext = NULL;
    479     }
    480 
    481     pIrp->IoStatus.Information = 0;
    482     pIrp->IoStatus.Status = STATUS_SUCCESS;
    483     IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    484 
    485     return STATUS_SUCCESS;
     892
     893#ifdef VBOX_WITH_HARDENING
     894    if (pDevObj == g_pDevObjStub)
     895    {
     896        PSUPDRVNTPROTECT pNtProtect = (PSUPDRVNTPROTECT)pFileObj->FsContext;
     897        Log(("VBoxDrvNtClose: pDevExt=%p pFileObj=%p pNtProtect=%p\n", pDevExt, pFileObj, pNtProtect));
     898        if (pNtProtect)
     899        {
     900            supdrvNtProtectRelease(pNtProtect);
     901            pFileObj->FsContext = NULL;
     902        }
     903    }
     904    else
     905#endif
     906    {
     907        PSUPDRVSESSION pSession = supdrvSessionHashTabLookup(pDevExt, RTProcSelf(), RTR0ProcHandleSelf(),
     908                                                             (PSUPDRVSESSION *)&pFileObj->FsContext);
     909        Log(("VBoxDrvNtCleanup: pDevExt=%p pFileObj=%p pSession=%p\n", pDevExt, pFileObj, pSession));
     910        if (pSession)
     911        {
     912            supdrvSessionHashTabRemove(pDevExt, pSession, NULL);
     913            supdrvSessionRelease(pSession); /* Drops the reference from supdrvSessionHashTabLookup. */
     914        }
     915    }
     916
     917    return supdrvNtCompleteRequest(STATUS_SUCCESS, pIrp);
    486918}
    487919
     
    510942{
    511943    PSUPDRVDEVEXT   pDevExt  = SUPDRVNT_GET_DEVEXT(pDevObj);
    512     PSUPDRVSESSION  pSession = (PSUPDRVSESSION)pFileObj->FsContext;
    513944
    514945    /*
    515      * Check the input a little bit.
     946     * Check the input a little bit and get a the session references.
    516947     */
     948    PSUPDRVSESSION  pSession = supdrvSessionHashTabLookup(pDevExt, RTProcSelf(), RTR0ProcHandleSelf(),
     949                                                          (PSUPDRVSESSION *)&pFileObj->FsContext);
    517950    if (!pSession)
    518951    {
    519         pIoStatus->Status      = STATUS_INVALID_PARAMETER;
     952        pIoStatus->Status      = STATUS_TRUST_FAILURE;
    520953        pIoStatus->Information = 0;
    521954        return TRUE;
    522955    }
    523956
    524     /*
    525      * Deal with the 2-3 high-speed IOCtl that takes their arguments from
    526      * the session and iCmd, and does not return anything.
    527      */
    528     if (   (   uCmd == SUP_IOCTL_FAST_DO_RAW_RUN
     957    if (pSession->fUnrestricted)
     958    {
     959#if defined(VBOX_WITH_HARDENING) && !defined(VBOX_WITHOUT_DEBUGGER_CHECKS)
     960        if (supdrvNtIsDebuggerAttached())
     961        {
     962            pIoStatus->Status      = STATUS_TRUST_FAILURE;
     963            pIoStatus->Information = 0;
     964            supdrvSessionRelease(pSession);
     965            return TRUE;
     966        }
     967#endif
     968
     969        /*
     970         * Deal with the 2-3 high-speed IOCtl that takes their arguments from
     971         * the session and iCmd, and does not return anything.
     972         */
     973        if (   uCmd == SUP_IOCTL_FAST_DO_RAW_RUN
    529974            || uCmd == SUP_IOCTL_FAST_DO_HM_RUN
    530975            || uCmd == SUP_IOCTL_FAST_DO_NOP)
    531         && pSession->fUnrestricted == true)
    532     {
    533         int rc = supdrvIOCtlFast(uCmd, (unsigned)(uintptr_t)pvOutput /* VMCPU id */, pDevExt, pSession);
    534         pIoStatus->Status      = RT_SUCCESS(rc) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER;
    535         pIoStatus->Information = 0; /* Could be used to pass rc if we liked. */
    536         return TRUE;
     976        {
     977            int rc = supdrvIOCtlFast(uCmd, (unsigned)(uintptr_t)pvOutput/* VMCPU id */, pDevExt, pSession);
     978            pIoStatus->Status      = RT_SUCCESS(rc) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER;
     979            pIoStatus->Information = 0; /* Could be used to pass rc if we liked. */
     980            supdrvSessionRelease(pSession);
     981            return TRUE;
     982        }
    537983    }
    538984
     
    546992          pDevExt, uCmd, pvInput, cbInput, pvOutput, cbOutput, pSession));
    547993
    548 #ifdef RT_ARCH_AMD64
     994# ifdef RT_ARCH_AMD64
    549995    /* Don't allow 32-bit processes to do any I/O controls. */
    550996    if (!IoIs32bitProcess(NULL))
    551 #endif
     997# endif
    552998    {
    553999        /*
     
    6551101        }
    6561102    }
     1103# ifdef RT_ARCH_AMD64
     1104    else
     1105    {
     1106        Log(("VBoxDrvNtFastIoDeviceControl: WOW64 req - not supported\n"));
     1107        rcNt = STATUS_NOT_SUPPORTED;
     1108    }
     1109# endif
     1110
     1111    /* complete the request. */
     1112    pIoStatus->Status = rcNt;
     1113    pIoStatus->Information = cbOut;
     1114    supdrvSessionRelease(pSession);
     1115    return TRUE; /* handled. */
     1116}
     1117#endif /* VBOXDRV_WITH_FAST_IO */
     1118
     1119
     1120#ifdef VBOXDRV_WITH_FAST_IO
     1121/**
     1122 * Fast I/O device control callback.
     1123 *
     1124 * This performs no buffering, neither on the way in or out.
     1125 *
     1126 * @returns TRUE if handled, FALSE if the normal I/O control routine should be
     1127 *          called.
     1128 * @param   pFileObj            The file object.
     1129 * @param   fWait               Whether it's a blocking call
     1130 * @param   pvInput             The input buffer as specified by the user.
     1131 * @param   cbInput             The size of the input buffer.
     1132 * @param   pvOutput            The output buffer as specfied by the user.
     1133 * @param   cbOutput            The size of the output buffer.
     1134 * @param   uFunction           The function.
     1135 * @param   pIoStatus           Where to return the status of the operation.
     1136 * @param   pDevObj             The device object..
     1137 */
     1138static BOOLEAN _stdcall VBoxDrvNtFastIoDeviceControl(PFILE_OBJECT pFileObj, BOOLEAN fWait, PVOID pvInput, ULONG cbInput,
     1139                                                     PVOID pvOutput, ULONG cbOutput, ULONG uCmd,
     1140                                                     PIO_STATUS_BLOCK pIoStatus, PDEVICE_OBJECT pDevObj)
     1141{
     1142    PSUPDRVDEVEXT   pDevExt  = SUPDRVNT_GET_DEVEXT(pDevObj);
     1143    PSUPDRVSESSION  pSession = (PSUPDRVSESSION)pFileObj->FsContext;
     1144
     1145    /*
     1146     * Check the input a little bit.
     1147     */
     1148    if (!pSession)
     1149    {
     1150        pIoStatus->Status      = STATUS_INVALID_PARAMETER;
     1151        pIoStatus->Information = 0;
     1152        return TRUE;
     1153    }
     1154
     1155    /*
     1156     * Deal with the 2-3 high-speed IOCtl that takes their arguments from
     1157     * the session and iCmd, and does not return anything.
     1158     */
     1159    if (   (   uCmd == SUP_IOCTL_FAST_DO_RAW_RUN
     1160            || uCmd == SUP_IOCTL_FAST_DO_HM_RUN
     1161            || uCmd == SUP_IOCTL_FAST_DO_NOP)
     1162        && pSession->fUnrestricted == true)
     1163    {
     1164        int rc = supdrvIOCtlFast(uCmd, (unsigned)(uintptr_t)pvOutput /* VMCPU id */, pDevExt, pSession);
     1165        pIoStatus->Status      = RT_SUCCESS(rc) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER;
     1166        pIoStatus->Information = 0; /* Could be used to pass rc if we liked. */
     1167        return TRUE;
     1168    }
     1169
     1170    /*
     1171     * The normal path.
     1172     */
     1173    NTSTATUS    rcNt;
     1174    unsigned    cbOut = 0;
     1175    int         rc = 0;
     1176    Log2(("VBoxDrvNtFastIoDeviceControl(%p): ioctl=%#x pvIn=%p cbIn=%#x pvOut=%p cbOut=%#x pSession=%p\n",
     1177          pDevExt, uCmd, pvInput, cbInput, pvOutput, cbOutput, pSession));
     1178
     1179#ifdef RT_ARCH_AMD64
     1180    /* Don't allow 32-bit processes to do any I/O controls. */
     1181    if (!IoIs32bitProcess(NULL))
     1182#endif
     1183    {
     1184        /*
     1185         * In this fast I/O device control path we have to do our own buffering.
     1186         */
     1187        /* Verify that the I/O control function matches our pattern. */
     1188        if ((uCmd & 0x3) == METHOD_BUFFERED)
     1189        {
     1190            /* Get the header so we can validate it a little bit against the
     1191               parameters before allocating any memory kernel for the reqest. */
     1192            SUPREQHDR Hdr;
     1193            if (cbInput >= sizeof(Hdr) && cbOutput >= sizeof(Hdr))
     1194            {
     1195                __try
     1196                {
     1197                    RtlCopyMemory(&Hdr, pvInput, sizeof(Hdr));
     1198                    rcNt = STATUS_SUCCESS;
     1199                }
     1200                __except(EXCEPTION_EXECUTE_HANDLER)
     1201                {
     1202                    rcNt = GetExceptionCode();
     1203                }
     1204            }
     1205            else
     1206                rcNt = STATUS_INVALID_PARAMETER;
     1207            if (NT_SUCCESS(rcNt))
     1208            {
     1209                /* Verify that the sizes in the request header are correct. */
     1210                ULONG cbBuf = RT_MAX(cbInput, cbOutput);
     1211                if (   cbInput  == Hdr.cbIn
     1212                    && cbOutput == Hdr.cbOut
     1213                    && cbBuf < _1M*16)
     1214                {
     1215                    /* Allocate a buffer and copy all the input into it. */
     1216                    PSUPREQHDR pHdr = (PSUPREQHDR)ExAllocatePoolWithTag(NonPagedPool, cbBuf, 'VBox');
     1217                    if (pHdr)
     1218                    {
     1219                        __try
     1220                        {
     1221                            RtlCopyMemory(pHdr, pvInput, cbInput);
     1222                            if (cbInput < cbBuf)
     1223                                RtlZeroMemory((uint8_t *)pHdr + cbInput, cbBuf - cbInput);
     1224                            rcNt = STATUS_SUCCESS;
     1225                        }
     1226                        __except(EXCEPTION_EXECUTE_HANDLER)
     1227                        {
     1228                            rcNt = GetExceptionCode();
     1229                        }
     1230                    }
     1231                    else
     1232                        rcNt = STATUS_NO_MEMORY;
     1233                    if (NT_SUCCESS(rcNt))
     1234                    {
     1235                        /*
     1236                         * Now call the common code to do the real work.
     1237                         */
     1238                        rc = supdrvIOCtl(uCmd, pDevExt, pSession, pHdr);
     1239                        if (RT_SUCCESS(rc))
     1240                        {
     1241                            /*
     1242                             * Copy back the result.
     1243                             */
     1244                            cbOut = pHdr->cbOut;
     1245                            if (cbOut > cbOutput)
     1246                            {
     1247                                cbOut = cbOutput;
     1248                                OSDBGPRINT(("VBoxDrvNtFastIoDeviceControl: too much output! %#x > %#x; uCmd=%#x!\n",
     1249                                            pHdr->cbOut, cbOut, uCmd));
     1250                            }
     1251                            if (cbOut)
     1252                            {
     1253                                __try
     1254                                {
     1255                                    RtlCopyMemory(pvOutput, pHdr, cbOut);
     1256                                    rcNt = STATUS_SUCCESS;
     1257                                }
     1258                                __except(EXCEPTION_EXECUTE_HANDLER)
     1259                                {
     1260                                    rcNt = GetExceptionCode();
     1261                                }
     1262                            }
     1263                            else
     1264                                rcNt = STATUS_SUCCESS;
     1265                        }
     1266                        else if (rc == VERR_INVALID_PARAMETER)
     1267                            rcNt = STATUS_INVALID_PARAMETER;
     1268                        else
     1269                            rcNt = STATUS_NOT_SUPPORTED;
     1270                        Log2(("VBoxDrvNtFastIoDeviceControl: returns %#x cbOut=%d rc=%#x\n", rcNt, cbOut, rc));
     1271                    }
     1272                    ExFreePoolWithTag(pHdr, 'VBox');
     1273                }
     1274                else
     1275                {
     1276                    Log(("VBoxDrvNtFastIoDeviceControl: Mismatching sizes (%#x) - Hdr=%#lx/%#lx Irp=%#lx/%#lx!\n",
     1277                         uCmd, Hdr.cbIn, Hdr.cbOut, cbInput, cbOutput));
     1278                    rcNt = STATUS_INVALID_PARAMETER;
     1279                }
     1280            }
     1281        }
     1282        else
     1283        {
     1284            Log(("VBoxDrvNtFastIoDeviceControl: not buffered request (%#x) - not supported\n", uCmd));
     1285            rcNt = STATUS_NOT_SUPPORTED;
     1286        }
     1287    }
    6571288#ifdef RT_ARCH_AMD64
    6581289    else
     
    6791310NTSTATUS _stdcall VBoxDrvNtDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
    6801311{
     1312    VBOXDRV_COMPLETE_IRP_AND_RETURN_IF_STUB_DEV(pDevObj, pIrp);
     1313
    6811314    PSUPDRVDEVEXT       pDevExt  = SUPDRVNT_GET_DEVEXT(pDevObj);
    6821315    PIO_STACK_LOCATION  pStack   = IoGetCurrentIrpStackLocation(pIrp);
    683     PSUPDRVSESSION      pSession = (PSUPDRVSESSION)pStack->FileObject->FsContext;
     1316    PSUPDRVSESSION      pSession = supdrvSessionHashTabLookup(pDevExt, RTProcSelf(), RTR0ProcHandleSelf(),
     1317                                                              (PSUPDRVSESSION *)&pStack->FileObject->FsContext);
     1318
     1319    if (!RT_VALID_PTR(pSession))
     1320        return supdrvNtCompleteRequest(STATUS_TRUST_FAILURE, pIrp);
    6841321
    6851322    /*
     
    6871324     * the session and iCmd, and does not return anything.
    6881325     */
    689     ULONG ulCmd = pStack->Parameters.DeviceIoControl.IoControlCode;
    690     if (   (   ulCmd == SUP_IOCTL_FAST_DO_RAW_RUN
     1326    if (pSession->fUnrestricted)
     1327    {
     1328#if defined(VBOX_WITH_HARDENING) && !defined(VBOX_WITHOUT_DEBUGGER_CHECKS)
     1329        if (supdrvNtIsDebuggerAttached())
     1330        {
     1331            supdrvSessionRelease(pSession);
     1332            return supdrvNtCompleteRequest(STATUS_TRUST_FAILURE, pIrp);
     1333        }
     1334#endif
     1335
     1336        ULONG ulCmd = pStack->Parameters.DeviceIoControl.IoControlCode;
     1337        if (   ulCmd == SUP_IOCTL_FAST_DO_RAW_RUN
    6911338            || ulCmd == SUP_IOCTL_FAST_DO_HM_RUN
    6921339            || ulCmd == SUP_IOCTL_FAST_DO_NOP)
    693         && pSession->fUnrestricted == true)
    694     {
    695         int rc = supdrvIOCtlFast(ulCmd, (unsigned)(uintptr_t)pIrp->UserBuffer /* VMCPU id */, pDevExt, pSession);
    696 
    697         /* Complete the I/O request. */
    698         NTSTATUS rcNt = pIrp->IoStatus.Status = RT_SUCCESS(rc) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER;
    699         IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    700         return rcNt;
     1340        {
     1341            int rc = supdrvIOCtlFast(ulCmd, (unsigned)(uintptr_t)pIrp->UserBuffer /* VMCPU id */, pDevExt, pSession);
     1342
     1343            /* Complete the I/O request. */
     1344            supdrvSessionRelease(pSession);
     1345            return supdrvNtCompleteRequest(RT_SUCCESS(rc) ? STATUS_SUCCESS : STATUS_INVALID_PARAMETER, pIrp);
     1346        }
    7011347    }
    7021348
     
    7871433    pIrp->IoStatus.Status = rcNt;
    7881434    pIrp->IoStatus.Information = cbOut;
     1435    supdrvSessionRelease(pSession);
    7891436    IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    7901437    return rcNt;
     
    8001447NTSTATUS _stdcall VBoxDrvNtInternalDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
    8011448{
     1449    VBOXDRV_COMPLETE_IRP_AND_RETURN_IF_STUB_DEV(pDevObj, pIrp);
     1450
    8021451    PSUPDRVDEVEXT       pDevExt  = SUPDRVNT_GET_DEVEXT(pDevObj);
    8031452    PIO_STACK_LOCATION  pStack   = IoGetCurrentIrpStackLocation(pIrp);
     
    9251574        RTPowerSignalEvent(((unsigned)pArgument2 == 0) ? RTPOWEREVENT_SUSPEND : RTPOWEREVENT_RESUME);
    9261575    }
     1576}
     1577
     1578
     1579/**
     1580 * Called to clean up the session structure before it's freed.
     1581 *
     1582 * @param   pDevExt             The device globals.
     1583 * @param   pSession            The session that's being cleaned up.
     1584 */
     1585void VBOXCALL supdrvOSCleanupSession(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession)
     1586{
     1587#ifdef VBOX_WITH_HARDENING
     1588    if (pSession->pNtProtect)
     1589    {
     1590        supdrvNtProtectRelease(pSession->pNtProtect);
     1591        pSession->pNtProtect = NULL;
     1592    }
     1593#endif
     1594}
     1595
     1596
     1597void VBOXCALL supdrvOSSessionHashTabInserted(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     1598{
     1599    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
     1600}
     1601
     1602
     1603void VBOXCALL supdrvOSSessionHashTabRemoved(PSUPDRVDEVEXT pDevExt, PSUPDRVSESSION pSession, void *pvUser)
     1604{
     1605    NOREF(pDevExt); NOREF(pSession); NOREF(pvUser);
    9271606}
    9281607
     
    10821761                    rc = VERR_LDR_IMPORTED_SYMBOL_NOT_FOUND;
    10831762                    break;
    1084                 case    0xC0000428 /* STATUS_INVALID_IMAGE_HASH */ :
     1763                case /* 0xC0000428 */ STATUS_INVALID_IMAGE_HASH:
    10851764                    rc = VERR_LDR_IMAGE_HASH;
    10861765                    break;
    1087                 case    0xC000010E /* STATUS_IMAGE_ALREADY_LOADED */ :
     1766                case /* 0xC000010E */ STATUS_IMAGE_ALREADY_LOADED:
    10881767                    Log(("WARNING: see @bugref{4853} for cause of this failure on Windows 7 x64\n"));
    10891768                    rc = VERR_ALREADY_LOADED;
     
    15092188    }
    15102189
     2190    if (rc < 0)
     2191    {
     2192        if (((uint32_t)rc & UINT32_C(0xffff0000)) == UINT32_C(0xffff0000))
     2193            return (NTSTATUS)( ((uint32_t)rc & UINT32_C(0xffff))
     2194                              | UINT32_C(0xe9860000) ); /* STATUS_SEVERITY_ERROR + C-bit + facility 0x986 */
     2195    }
    15112196    return STATUS_UNSUCCESSFUL;
    15122197}
     
    15472232}
    15482233#endif
     2234
     2235
     2236#ifdef VBOX_WITH_HARDENING
     2237
     2238/** @name Identifying Special Processes: CSRSS.EXE
     2239 * @{ */
     2240
     2241
     2242/**
     2243 * Checks if the process is a system32 process by the given name.
     2244 *
     2245 * @returns true / false.
     2246 * @param   pProcess            The process to check.
     2247 * @param   pszName             The lower case process name (no path!).
     2248 */
     2249static bool supdrvNtProtectIsSystem32ProcessMatch(PEPROCESS pProcess, const char *pszName)
     2250{
     2251    Assert(strlen(pszName) < 16); /* see buffer below */
     2252
     2253    /*
     2254     * This test works on XP+.
     2255     */
     2256    const char *pszImageFile = (const char *)PsGetProcessImageFileName(pProcess);
     2257    if (!pszImageFile)
     2258        return false;
     2259
     2260    if (RTStrICmp(pszImageFile, pszName) != 0)
     2261        return false;
     2262
     2263    /*
     2264     * This test requires a Vista+ API.
     2265     */
     2266    if (g_pfnPsReferenceProcessFilePointer)
     2267    {
     2268        PFILE_OBJECT pFile = NULL;
     2269        NTSTATUS rcNt = g_pfnPsReferenceProcessFilePointer(pProcess, &pFile);
     2270        if (!NT_SUCCESS(rcNt))
     2271            return false;
     2272
     2273        union
     2274        {
     2275            OBJECT_NAME_INFORMATION Info;
     2276            uint8_t        abBuffer[sizeof(g_System32NtPath) + 16 * sizeof(WCHAR)];
     2277        } Buf;
     2278        ULONG cbIgn;
     2279        rcNt = ObQueryNameString(pFile, &Buf.Info, sizeof(Buf) - sizeof(WCHAR), &cbIgn);
     2280        ObDereferenceObject(pFile);
     2281        if (!NT_SUCCESS(rcNt))
     2282            return false;
     2283
     2284        /* Terminate the name. */
     2285        PRTUTF16 pwszName = Buf.Info.Name.Buffer;
     2286        pwszName[Buf.Info.Name.Length / sizeof(RTUTF16)] = '\0';
     2287
     2288        /* Match the name against the system32 directory path. */
     2289        uint32_t cbSystem32 = g_System32NtPath.UniStr.Length;
     2290        if (Buf.Info.Name.Length < cbSystem32)
     2291            return false;
     2292        if (memcmp(pwszName, g_System32NtPath.UniStr.Buffer, cbSystem32))
     2293            return false;
     2294        pwszName += cbSystem32 / sizeof(RTUTF16);
     2295        if (*pwszName++ != '\\')
     2296            return false;
     2297
     2298        /* Compare the name. */
     2299        const char *pszRight = pszName;
     2300        for (;;)
     2301        {
     2302            WCHAR wchLeft = *pwszName++;
     2303            char  chRight = *pszRight++;
     2304            Assert(chRight == RT_C_TO_LOWER(chRight));
     2305
     2306            if (   wchLeft != chRight
     2307                && RT_C_TO_LOWER(wchLeft) != chRight)
     2308                return false;
     2309            if (!chRight)
     2310                break;
     2311        }
     2312    }
     2313
     2314    return true;
     2315}
     2316
     2317
     2318/**
     2319 * Checks if the current process is likely to be CSRSS.
     2320 *
     2321 * @returns true/false.
     2322 * @param   pProcess        The process.
     2323 */
     2324static bool supdrvNtProtectIsCsrssByProcess(PEPROCESS pProcess)
     2325{
     2326    /*
     2327     * On Windows 8.1 CSRSS.EXE is a protected process.
     2328     */
     2329    if (g_pfnPsIsProtectedProcessLight)
     2330    {
     2331        if (!g_pfnPsIsProtectedProcessLight(pProcess))
     2332            return false;
     2333    }
     2334
     2335    /*
     2336     * The name tests.
     2337     */
     2338    if (!supdrvNtProtectIsSystem32ProcessMatch(pProcess, "csrss.exe"))
     2339        return false;
     2340
     2341    /** @todo Could extend the CSRSS.EXE check with that the TokenUser of the
     2342     *        current process must be "NT AUTHORITY\SYSTEM" (S-1-5-18). */
     2343
     2344    return true;
     2345}
     2346
     2347
     2348/**
     2349 * Called in the context of VBoxDrvNtCreate to determin the CSRSS for the
     2350 * current process.
     2351 *
     2352 * The Client/Server Runtime Subsystem (CSRSS) process needs to be allowed some
     2353 * additional access right so we need to make 101% sure we correctly identify
     2354 * the CSRSS process a process is associated with.
     2355 *
     2356 * @returns IPRT status code.
     2357 * @param   pNtProtect          The NT protected process structure. The
     2358 *                              hCsrssPid member will be updated on success.
     2359 */
     2360static int supdrvNtProtectFindAssociatedCsrss(PSUPDRVNTPROTECT pNtProtect)
     2361{
     2362    Assert(pNtProtect->AvlCore.Key == PsGetCurrentProcessId());
     2363    Assert(pNtProtect->pCsrssProcess == NULL);
     2364    Assert(pNtProtect->hCsrssPid == NULL);
     2365
     2366    /*
     2367     * We'll try use the ApiPort LPC object for the session we're in to track
     2368     * down the CSRSS process. So, we start by constructing a path to it.
     2369     */
     2370    int rc;
     2371    uint32_t    uSessionId = PsGetProcessSessionId(PsGetCurrentProcess());
     2372    WCHAR       wszApiPort[48];
     2373    if (uSessionId == 0)
     2374        rc = RTUtf16CopyAscii(wszApiPort, RT_ELEMENTS(wszApiPort), "\\Windows\\ApiPort");
     2375    else
     2376    {
     2377        char szTmp[64];
     2378        ssize_t cchTmp = RTStrFormatU32(szTmp, sizeof(szTmp), uSessionId, 10, 0, 0, 0);
     2379        AssertReturn(cchTmp > 0, (int)cchTmp);
     2380        rc = RTUtf16CopyAscii(wszApiPort, RT_ELEMENTS(wszApiPort), "\\Sessions\\");
     2381        if (RT_SUCCESS(rc))
     2382            rc = RTUtf16CatAscii(wszApiPort, RT_ELEMENTS(wszApiPort), szTmp);
     2383        if (RT_SUCCESS(rc))
     2384            rc = RTUtf16CatAscii(wszApiPort, RT_ELEMENTS(wszApiPort), "\\Windows\\ApiPort");
     2385    }
     2386    AssertRCReturn(rc, rc);
     2387
     2388    UNICODE_STRING ApiPortStr;
     2389    ApiPortStr.Buffer = wszApiPort;
     2390    ApiPortStr.Length = (USHORT)(RTUtf16Len(wszApiPort) * sizeof(RTUTF16));
     2391    ApiPortStr.MaximumLength = ApiPortStr.Length + sizeof(RTUTF16);
     2392
     2393    /*
     2394     * The object cannot be opened, but we can reference it by name.
     2395     */
     2396    void *pvApiPortObj = NULL;
     2397    NTSTATUS rcNt = ObReferenceObjectByName(&ApiPortStr,
     2398                                            0,
     2399                                            NULL /*pAccessState*/,
     2400                                            STANDARD_RIGHTS_READ,
     2401                                            *LpcPortObjectType,
     2402                                            KernelMode,
     2403                                            NULL /*pvParseContext*/,
     2404                                            &pvApiPortObj);
     2405    if (!NT_SUCCESS(rcNt))
     2406    {
     2407        SUPR0Printf("vboxdrv: Error opening '%ls': %#x\n", wszApiPort, rcNt);
     2408        return VERR_SUPDRV_APIPORT_OPEN_ERROR;
     2409    }
     2410
     2411    /*
     2412     * Query the processes in the system so we can locate CSRSS.EXE candidates.
     2413     * Note! Attempts at using SystemSessionProcessInformation failed with
     2414     *       STATUS_ACCESS_VIOLATION.
     2415     */
     2416    ULONG       cbNeeded = _64K;
     2417    uint32_t    cbBuf;
     2418    uint8_t    *pbBuf = NULL;
     2419    do
     2420    {
     2421        cbBuf = RT_ALIGN(cbNeeded + _4K, _64K);
     2422        pbBuf = (uint8_t *)RTMemAlloc(cbBuf);
     2423        if (!pbBuf)
     2424            break;
     2425
     2426        cbNeeded = 0;
     2427#if 0 /* doesn't work. */
     2428        SYSTEM_SESSION_PROCESS_INFORMATION Req;
     2429        Req.SessionId    = uSessionId;
     2430        Req.BufferLength = cbBuf;
     2431        Req.Buffer       = pbBuf;
     2432        rcNt = NtQuerySystemInformation(SystemSessionProcessInformation, &Req, sizeof(Req), &cbNeeded);
     2433#else
     2434        rcNt = NtQuerySystemInformation(SystemProcessInformation, pbBuf, cbBuf, &cbNeeded);
     2435#endif
     2436        if (NT_SUCCESS(rcNt))
     2437            break;
     2438
     2439        RTMemFree(pbBuf);
     2440        pbBuf = NULL;
     2441    } while (   rcNt == STATUS_INFO_LENGTH_MISMATCH
     2442             && cbNeeded > cbBuf
     2443             && cbNeeded < 32U*_1M);
     2444
     2445    if (   pbBuf
     2446        && NT_SUCCESS(rcNt)
     2447        && cbNeeded >= sizeof(SYSTEM_PROCESS_INFORMATION))
     2448    {
     2449        /*
     2450         * Walk the returned data and look for the process associated with the
     2451         * ApiPort object.  The ApiPort object keeps the EPROCESS address of
     2452         * the owner process (i.e. CSRSS) relatively early in the structure. On
     2453         * 64-bit windows 8.1 it's at offset 0x18.  So, obtain the EPROCESS
     2454         * pointer to likely CSRSS processes and check for a match in the first
     2455         * 0x40 bytes of the ApiPort object.
     2456         */
     2457        rc = VERR_SUPDRV_CSRSS_NOT_FOUND;
     2458        for (uint32_t offBuf = 0; offBuf <= cbNeeded - sizeof(SYSTEM_PROCESS_INFORMATION);)
     2459        {
     2460            PRTNT_SYSTEM_PROCESS_INFORMATION pProcInfo = (PRTNT_SYSTEM_PROCESS_INFORMATION)&pbBuf[offBuf];
     2461            if (   pProcInfo->ProcessName.Length == 9 * sizeof(WCHAR)
     2462                && pProcInfo->NumberOfThreads > 2   /* Very low guess. */
     2463                && pProcInfo->HandleCount     > 32  /* Very low guess, I hope. */
     2464                && (uintptr_t)pProcInfo->ProcessName.Buffer - (uintptr_t)pbBuf < cbNeeded
     2465                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[0]) == 'c'
     2466                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[1]) == 's'
     2467                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[2]) == 'r'
     2468                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[3]) == 's'
     2469                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[4]) == 's'
     2470                &&               pProcInfo->ProcessName.Buffer[5]  == '.'
     2471                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[6]) == 'e'
     2472                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[7]) == 'x'
     2473                && RT_C_TO_LOWER(pProcInfo->ProcessName.Buffer[8]) == 'e' )
     2474            {
     2475
     2476                /* Get the process structure and perform some more thorough
     2477                   process checks. */
     2478                PEPROCESS pProcess;
     2479                rcNt = PsLookupProcessByProcessId(pProcInfo->UniqueProcessId, &pProcess);
     2480                if (NT_SUCCESS(rcNt))
     2481                {
     2482                    if (supdrvNtProtectIsCsrssByProcess(pProcess))
     2483                    {
     2484                        if (PsGetProcessSessionId(pProcess) == uSessionId)
     2485                        {
     2486                            /* Final test, check the ApiPort.
     2487                               Note! The old LPC (pre Vista) objects has the PID
     2488                                     much earlier in the structure.  Might be
     2489                                     worth looking for it instead. */
     2490                            bool fThatsIt = false;
     2491                            __try
     2492                            {
     2493                                PEPROCESS *ppPortProc = (PEPROCESS *)pvApiPortObj;
     2494                                uint32_t   cTests = g_uNtVerCombined >= SUP_NT_VER_VISTA ? 16 : 38; /* ALPC since Vista. */
     2495                                do
     2496                                {
     2497                                    fThatsIt = *ppPortProc == pProcess;
     2498                                    ppPortProc++;
     2499                                } while (!fThatsIt && --cTests > 0);
     2500                            }
     2501                            __except(EXCEPTION_EXECUTE_HANDLER)
     2502                            {
     2503                                fThatsIt = false;
     2504                            }
     2505                            if (fThatsIt)
     2506                            {
     2507                                /* Ok, we found it!  Keep the process structure
     2508                                   reference as well as the PID so we can
     2509                                   safely identify it later on.  */
     2510                                pNtProtect->hCsrssPid     = pProcInfo->UniqueProcessId;
     2511                                pNtProtect->pCsrssProcess = pProcess;
     2512                                rc = VINF_SUCCESS;
     2513                                break;
     2514                            }
     2515                        }
     2516                    }
     2517
     2518                    ObDereferenceObject(pProcess);
     2519                }
     2520            }
     2521
     2522            /* Advance. */
     2523            if (!pProcInfo->NextEntryOffset)
     2524                break;
     2525            offBuf += pProcInfo->NextEntryOffset;
     2526        }
     2527    }
     2528    else
     2529        rc = VERR_SUPDRV_SESSION_PROCESS_ENUM_ERROR;
     2530    RTMemFree(pbBuf);
     2531    ObDereferenceObject(pvApiPortObj);
     2532    return rc;
     2533}
     2534
     2535
     2536/**
     2537 * Checks that the given process is the CSRSS process associated with protected
     2538 * process.
     2539 *
     2540 * @returns true / false.
     2541 * @param   pNtProtect          The NT protection structure.
     2542 * @param   pCsrss              The process structure of the alleged CSRSS.EXE
     2543 *                              process.
     2544 */
     2545static bool supdrvNtProtectIsAssociatedCsrss(PSUPDRVNTPROTECT pNtProtect, PEPROCESS pCsrss)
     2546{
     2547    if (pNtProtect->pCsrssProcess == pCsrss)
     2548    {
     2549        if (pNtProtect->hCsrssPid == PsGetProcessId(pCsrss))
     2550        {
     2551            return true;
     2552        }
     2553    }
     2554    return false;
     2555}
     2556
     2557
     2558/**
     2559 * Checks if the given process is the stupid themes service.
     2560 *
     2561 * The caller does some screening of access masks and what not. We do the rest.
     2562 *
     2563 * @returns true / false.
     2564 * @param   pNtProtect          The NT protection structure.
     2565 * @param   pAnnoyingProcess    The process structure of an process that might
     2566 *                              happen to be the annoying themes process.
     2567 */
     2568static bool supdrvNtProtectIsFrigginThemesService(PSUPDRVNTPROTECT pNtProtect, PEPROCESS pAnnoyingProcess)
     2569{
     2570    /*
     2571     * Check the process name.
     2572     */
     2573    if (!supdrvNtProtectIsSystem32ProcessMatch(pAnnoyingProcess, "svchost.exe"))
     2574        return false;
     2575
     2576    /** @todo Come up with more checks. */
     2577
     2578    return true;
     2579}
     2580
     2581
     2582/** @} */
     2583
     2584
     2585/** @name Process Creation Callbacks.
     2586 * @{ */
     2587
     2588/**
     2589 * Common worker used by the process creation hooks as well as the process
     2590 * handle creation hooks to check if a VM process is being created.
     2591 *
     2592 * @returns true if likely to be a VM process, false if not.
     2593 * @param   pNtStub             The NT protection structure for the possible
     2594 *                              stub process.
     2595 * @param   hParentPid          The parent pid.
     2596 * @param   hChildPid           The child pid.
     2597 */
     2598static bool supdrvNtProtectIsSpawningStubProcess(PSUPDRVNTPROTECT pNtStub, HANDLE hParentPid, HANDLE hChildPid)
     2599{
     2600    bool fRc = false;
     2601    if (pNtStub->AvlCore.Key == hParentPid) /* paranoia */
     2602    {
     2603        if (pNtStub->enmProcessKind == kSupDrvNtProtectKind_StubSpawning)
     2604        {
     2605            /* Compare short names. */
     2606            PEPROCESS pStubProcess;
     2607            NTSTATUS rcNt = PsLookupProcessByProcessId(hParentPid, &pStubProcess);
     2608            if (NT_SUCCESS(rcNt))
     2609            {
     2610                PEPROCESS pChildProcess;
     2611                rcNt = PsLookupProcessByProcessId(hChildPid, &pChildProcess);
     2612                if (NT_SUCCESS(rcNt))
     2613                {
     2614                    const char *pszStub  = (const char *)PsGetProcessImageFileName(pStubProcess);
     2615                    const char *pszChild = (const char *)PsGetProcessImageFileName(pChildProcess);
     2616                    fRc = pszStub != NULL
     2617                       && pszChild != NULL
     2618                       && strcmp(pszStub, pszChild) == 0;
     2619
     2620                    /** @todo check that the full image names matches. */
     2621
     2622                    ObDereferenceObject(pChildProcess);
     2623                }
     2624                ObDereferenceObject(pStubProcess);
     2625            }
     2626        }
     2627    }
     2628    return fRc;
     2629}
     2630
     2631
     2632/**
     2633 * Common code used by the notifies to protect a child process.
     2634 *
     2635 * @returns VBox status code.
     2636 * @param   pNtStub             The NT protect structure for the parent.
     2637 * @param   hChildPid           The child pid.
     2638 */
     2639static int supdrvNtProtectProtectNewStubChild(PSUPDRVNTPROTECT pNtParent, HANDLE hChildPid)
     2640{
     2641    /*
     2642     * Create a child protection struction.
     2643     */
     2644    PSUPDRVNTPROTECT pNtChild;
     2645    int rc = supdrvNtProtectCreate(&pNtChild, hChildPid, kSupDrvNtProtectKind_VmProcessUnconfirmed, false /*fLink*/);
     2646    if (RT_SUCCESS(rc))
     2647    {
     2648        pNtChild->fFirstProcessCreateHandle = true;
     2649        pNtChild->fFirstThreadCreateHandle = true;
     2650        pNtChild->fCsrssFirstProcessCreateHandle = true;
     2651        pNtChild->fCsrssFirstProcessDuplicateHandle = true;
     2652        pNtChild->fThemesFirstProcessCreateHandle = true;
     2653        pNtChild->hParentPid = pNtParent->AvlCore.Key;
     2654        pNtChild->hCsrssPid = pNtParent->hCsrssPid;
     2655        pNtChild->pCsrssProcess = pNtParent->pCsrssProcess;
     2656        if (pNtChild->pCsrssProcess)
     2657            ObReferenceObject(pNtChild->pCsrssProcess);
     2658
     2659        /*
     2660         * Take the spinlock, recheck parent conditions and link things.
     2661         */
     2662        RTSpinlockAcquire(g_hNtProtectLock);
     2663        if (pNtParent->enmProcessKind == kSupDrvNtProtectKind_StubSpawning)
     2664        {
     2665            bool fSuccess = RTAvlPVInsert(&g_NtProtectTree, &pNtChild->AvlCore);
     2666            if (fSuccess)
     2667            {
     2668                pNtParent->u.pChild       = pNtChild; /* Parent keeps the initial reference. */
     2669                pNtParent->enmProcessKind = kSupDrvNtProtectKind_StubParent;
     2670                pNtChild->u.pParent       = pNtParent;
     2671
     2672                RTSpinlockRelease(g_hNtProtectLock);
     2673                return VINF_SUCCESS;
     2674            }
     2675
     2676            rc = VERR_INTERNAL_ERROR_2;
     2677        }
     2678        else
     2679            rc = VERR_WRONG_ORDER;
     2680        RTSpinlockRelease(g_hNtProtectLock);
     2681
     2682        supdrvNtProtectRelease(pNtChild);
     2683    }
     2684    return rc;
     2685}
     2686
     2687
     2688/**
     2689 * Common process termination code.
     2690 *
     2691 * Transitions protected process to the dead states, protecting against handle
     2692 * PID reuse (esp. with unconfirmed VM processes) and handle cleanup issues.
     2693 *
     2694 * @param   hDeadPid            The PID of the dead process.
     2695 */
     2696static void supdrvNtProtectUnprotectDeadProcess(HANDLE hDeadPid)
     2697{
     2698    PSUPDRVNTPROTECT pNtProtect = supdrvNtProtectLookup(hDeadPid);
     2699    if (pNtProtect)
     2700    {
     2701        PSUPDRVNTPROTECT pNtChild = NULL;
     2702
     2703        RTSpinlockAcquire(g_hNtProtectLock);
     2704
     2705        /*
     2706         * If this is an unconfirmed VM process, we must release the reference
     2707         * the parent structure holds.
     2708         */
     2709        if (pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed)
     2710        {
     2711            PSUPDRVNTPROTECT pNtParent = pNtProtect->u.pParent;
     2712            AssertRelease(pNtParent); AssertRelease(pNtParent->u.pChild == pNtProtect);
     2713            pNtParent->u.pChild   = NULL;
     2714            pNtProtect->u.pParent = NULL;
     2715            pNtChild = pNtProtect;
     2716        }
     2717        /*
     2718         * If this is a stub exitting before the VM process gets confirmed,
     2719         * release the protection of the potential VM process as this is not
     2720         * the prescribed behavior.
     2721         */
     2722        else if (   pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubParent
     2723                 && pNtProtect->u.pChild)
     2724        {
     2725            pNtChild = pNtProtect->u.pChild;
     2726            pNtProtect->u.pChild = NULL;
     2727            pNtChild->u.pParent  = NULL;
     2728            pNtChild->enmProcessKind = kSupDrvNtProtectKind_VmProcessDead;
     2729        }
     2730
     2731        /*
     2732         * Transition it to the dead state to prevent it from opening the
     2733         * support driver again or be posthumously abused as a vm process parent.
     2734         */
     2735        if (   pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed
     2736            || pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessConfirmed)
     2737            pNtProtect->enmProcessKind = kSupDrvNtProtectKind_VmProcessDead;
     2738        else if (   pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubParent
     2739                 || pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubSpawning
     2740                 || pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubUnverified)
     2741            pNtProtect->enmProcessKind = kSupDrvNtProtectKind_StubDead;
     2742
     2743        RTSpinlockRelease(g_hNtProtectLock);
     2744
     2745        supdrvNtProtectRelease(pNtProtect);
     2746        supdrvNtProtectRelease(pNtChild);
     2747
     2748        /*
     2749         * Do session cleanups.
     2750         */
     2751        AssertReturnVoid((HANDLE)(uintptr_t)RTProcSelf() == hDeadPid);
     2752        if (g_pDevObjSys)
     2753        {
     2754            PSUPDRVDEVEXT  pDevExt  = (PSUPDRVDEVEXT)g_pDevObjSys->DeviceExtension;
     2755            PSUPDRVSESSION pSession = supdrvSessionHashTabLookup(pDevExt, (RTPROCESS)(uintptr_t)hDeadPid,
     2756                                                                 RTR0ProcHandleSelf(), NULL);
     2757            if (pSession)
     2758            {
     2759                supdrvSessionHashTabRemove(pDevExt, pSession, NULL);
     2760                supdrvSessionRelease(pSession); /* Drops the reference from supdrvSessionHashTabLookup. */
     2761            }
     2762        }
     2763    }
     2764}
     2765
     2766
     2767/**
     2768 * Common worker for the process creation callback that verifies a new child
     2769 * being created by the handle creation callback code.
     2770 *
     2771 * @param   pNtStub         The parent.
     2772 * @param   pNtVm           The child.
     2773 * @param   fCallerChecks   The result of any additional tests the caller made.
     2774 *                          This is in order to avoid duplicating the failure
     2775 *                          path code.
     2776 */
     2777static void supdrvNtProtectVerifyNewChildProtection(PSUPDRVNTPROTECT pNtStub, PSUPDRVNTPROTECT pNtVm, bool fCallerChecks)
     2778{
     2779    if (   fCallerChecks
     2780        && pNtStub->enmProcessKind == kSupDrvNtProtectKind_StubParent
     2781        && pNtVm->enmProcessKind   == kSupDrvNtProtectKind_VmProcessUnconfirmed
     2782        && pNtVm->u.pParent        == pNtStub
     2783        && pNtStub->u.pChild       == pNtVm)
     2784    {
     2785        /* Fine, nothing to do. */
     2786        return;
     2787    }
     2788
     2789    LogRel(("vboxdrv: Misdetected vm stub; hParentPid=%p hChildPid=%p\n", pNtStub->AvlCore.Key, pNtVm->AvlCore.Key));
     2790    if (pNtStub->enmProcessKind != kSupDrvNtProtectKind_VmProcessConfirmed)
     2791        supdrvNtProtectUnprotectDeadProcess(pNtVm->AvlCore.Key);
     2792}
     2793
     2794
     2795/**
     2796 * Old style callback (since forever).
     2797 *
     2798 * @param   hParentPid          The parent PID.
     2799 * @param   hNewPid             The PID of the new child.
     2800 * @param   fCreated            TRUE if it's a creation notification,
     2801 *                              FALSE if termination.
     2802 * @remarks ASSUMES this arrives before the handle creation callback.
     2803 */
     2804static VOID __stdcall
     2805supdrvNtProtectCallback_ProcessCreateNotify(HANDLE hParentPid, HANDLE hNewPid, BOOLEAN fCreated)
     2806{
     2807    /*
     2808     * Is it a new process that needs protection?
     2809     */
     2810    if (fCreated)
     2811    {
     2812        PSUPDRVNTPROTECT pNtStub = supdrvNtProtectLookup(hParentPid);
     2813        if (pNtStub)
     2814        {
     2815            PSUPDRVNTPROTECT pNtVm = supdrvNtProtectLookup(hNewPid);
     2816            if (!pNtVm)
     2817            {
     2818                if (supdrvNtProtectIsSpawningStubProcess(pNtStub, hParentPid, hNewPid))
     2819                    supdrvNtProtectProtectNewStubChild(pNtStub, hNewPid);
     2820            }
     2821            else
     2822            {
     2823                supdrvNtProtectVerifyNewChildProtection(pNtStub, pNtVm, true);
     2824                supdrvNtProtectRelease(pNtVm);
     2825            }
     2826            supdrvNtProtectRelease(pNtStub);
     2827        }
     2828    }
     2829    /*
     2830     * Process termination, do clean ups.
     2831     */
     2832    else
     2833        supdrvNtProtectUnprotectDeadProcess(hNewPid);
     2834}
     2835
     2836
     2837/**
     2838 * New style callback (Vista SP1+ / w2k8).
     2839 *
     2840 * @param   pNewProcess         The new process.
     2841 * @param   hNewPid             The PID of the new process.
     2842 * @param   pInfo               Process creation details. NULL if process
     2843 *                              termination notification.
     2844 * @remarks ASSUMES this arrives before the handle creation callback.
     2845 */
     2846static VOID __stdcall
     2847supdrvNtProtectCallback_ProcessCreateNotifyEx(PEPROCESS pNewProcess, HANDLE hNewPid, PPS_CREATE_NOTIFY_INFO pInfo)
     2848{
     2849    /*
     2850     * Is it a new process that needs protection?
     2851     */
     2852    if (pInfo)
     2853    {
     2854        PSUPDRVNTPROTECT pNtStub = supdrvNtProtectLookup(pInfo->CreatingThreadId.UniqueProcess);
     2855
     2856        Log(("vboxdrv/NewProcessEx: ctx=%04zx/%p pid=%04zx ppid=%04zx ctor=%04zx/%04zx rcNt=%#x %.*ls\n",
     2857             PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     2858             hNewPid, pInfo->ParentProcessId,
     2859             pInfo->CreatingThreadId.UniqueProcess, pInfo->CreatingThreadId.UniqueThread, pInfo->CreationStatus,
     2860             pInfo->FileOpenNameAvailable && pInfo->ImageFileName ? (size_t)pInfo->ImageFileName->Length / 2 : 0,
     2861             pInfo->FileOpenNameAvailable && pInfo->ImageFileName ? pInfo->ImageFileName->Buffer : NULL));
     2862
     2863        if (pNtStub)
     2864        {
     2865            PSUPDRVNTPROTECT pNtVm = supdrvNtProtectLookup(hNewPid);
     2866            if (!pNtVm)
     2867            {
     2868                /* Parent must be creator. */
     2869                if (pInfo->CreatingThreadId.UniqueProcess == pInfo->ParentProcessId)
     2870                {
     2871                    if (supdrvNtProtectIsSpawningStubProcess(pNtStub, pInfo->ParentProcessId, hNewPid))
     2872                        supdrvNtProtectProtectNewStubChild(pNtStub, hNewPid);
     2873                }
     2874            }
     2875            else
     2876            {
     2877                /* Parent must be creator (as above). */
     2878                supdrvNtProtectVerifyNewChildProtection(pNtStub, pNtVm,
     2879                                                        pInfo->CreatingThreadId.UniqueProcess == pInfo->ParentProcessId);
     2880                supdrvNtProtectRelease(pNtVm);
     2881            }
     2882            supdrvNtProtectRelease(pNtStub);
     2883        }
     2884    }
     2885    /*
     2886     * Process termination, do clean ups.
     2887     */
     2888    else
     2889        supdrvNtProtectUnprotectDeadProcess(hNewPid);
     2890}
     2891
     2892/** @} */
     2893
     2894
     2895/** @name Process Handle Callbacks.
     2896 * @{ */
     2897
     2898/** Process rights that we allow for handles to stub and VM processes. */
     2899# define SUPDRV_NT_ALLOW_PROCESS_RIGHTS  \
     2900    (  PROCESS_TERMINATE \
     2901     | PROCESS_VM_READ \
     2902     | PROCESS_QUERY_INFORMATION \
     2903     | PROCESS_QUERY_LIMITED_INFORMATION \
     2904     | PROCESS_SUSPEND_RESUME \
     2905     | DELETE \
     2906     | READ_CONTROL \
     2907     | SYNCHRONIZE)
     2908
     2909/** Evil process rights. */
     2910# define SUPDRV_NT_EVIL_PROCESS_RIGHTS  \
     2911    (  PROCESS_CREATE_THREAD \
     2912     | PROCESS_SET_SESSIONID /*?*/ \
     2913     | PROCESS_VM_OPERATION \
     2914     | PROCESS_VM_WRITE \
     2915     | PROCESS_DUP_HANDLE \
     2916     | PROCESS_CREATE_PROCESS /*?*/ \
     2917     | PROCESS_SET_QUOTA /*?*/ \
     2918     | PROCESS_SET_INFORMATION \
     2919     | PROCESS_SET_LIMITED_INFORMATION /*?*/ \
     2920     | 0)
     2921AssertCompile((SUPDRV_NT_ALLOW_PROCESS_RIGHTS & SUPDRV_NT_EVIL_PROCESS_RIGHTS) == 0);
     2922
     2923
     2924static OB_PREOP_CALLBACK_STATUS __stdcall
     2925supdrvNtProtectCallback_ProcessHandlePre(PVOID pvUser, POB_PRE_OPERATION_INFORMATION pOpInfo)
     2926{
     2927    Assert(pvUser == NULL);
     2928    Assert(pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE || pOpInfo->Operation == OB_OPERATION_HANDLE_DUPLICATE);
     2929    Assert(pOpInfo->ObjectType == *PsProcessType);
     2930
     2931    /*
     2932     * Protected?  Kludge required for NtOpenProcess calls comming in before
     2933     * the create process hook triggers on Windows 8.1 (possibly others too).
     2934     */
     2935    HANDLE           hObjPid    = PsGetProcessId((PEPROCESS)pOpInfo->Object);
     2936    PSUPDRVNTPROTECT pNtProtect = supdrvNtProtectLookup(hObjPid);
     2937    if (!pNtProtect)
     2938    {
     2939        HANDLE           hParentPid = PsGetProcessInheritedFromUniqueProcessId((PEPROCESS)pOpInfo->Object);
     2940        PSUPDRVNTPROTECT pNtStub = supdrvNtProtectLookup(hParentPid);
     2941        if (pNtStub)
     2942        {
     2943            if (supdrvNtProtectIsSpawningStubProcess(pNtStub, hParentPid, hObjPid))
     2944            {
     2945                supdrvNtProtectProtectNewStubChild(pNtStub, hObjPid);
     2946                pNtProtect = supdrvNtProtectLookup(hObjPid);
     2947            }
     2948            supdrvNtProtectRelease(pNtStub);
     2949        }
     2950    }
     2951    pOpInfo->CallContext = pNtProtect; /* Just for reference. */
     2952    if (pNtProtect)
     2953    {
     2954        /*
     2955         * Ok, it's a protected process.  Strip rights as required or possible.
     2956         */
     2957        static ACCESS_MASK const s_fCsrssStupidDesires = 0x1fffff;
     2958        ACCESS_MASK fAllowedRights = SUPDRV_NT_ALLOW_PROCESS_RIGHTS;
     2959
     2960        if (pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE)
     2961        {
     2962            /* Don't restrict the process accessing itself. */
     2963            if ((PEPROCESS)pOpInfo->Object == PsGetCurrentProcess())
     2964            {
     2965                pOpInfo->CallContext = NULL; /* don't assert */
     2966                pNtProtect->fFirstProcessCreateHandle = false;
     2967
     2968                Log(("vboxdrv/ProcessHandlePre: ctx=%04zx/%p wants %#x to %p in pid=%04zx [%d] %s\n",
     2969                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     2970                     pOpInfo->Parameters->CreateHandleInformation.DesiredAccess,
     2971                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind,
     2972                     PsGetProcessImageFileName(PsGetCurrentProcess()) ));
     2973            }
     2974            else
     2975            {
     2976                /* Special case 1 on Vista, 7 & 8:
     2977                   The CreateProcess code passes the handle over to CSRSS.EXE
     2978                   and the code inBaseSrvCreateProcess will duplicate the
     2979                   handle with 0x1fffff as access mask.  NtDuplicateObject will
     2980                   fail this call before it ever gets down here.
     2981
     2982                   Special case 2 on 8.1:
     2983                   The CreateProcess code requires additional rights for
     2984                   something, we'll drop these in the stub code. */
     2985                if (   pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed
     2986                    && pNtProtect->fFirstProcessCreateHandle
     2987                    && pNtProtect->hParentPid == PsGetProcessId(PsGetCurrentProcess()))
     2988                {
     2989                    if (   !pOpInfo->KernelHandle
     2990                        && pOpInfo->Parameters->CreateHandleInformation.DesiredAccess == s_fCsrssStupidDesires)
     2991                    {
     2992                        if (g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 3))
     2993                            fAllowedRights |= s_fCsrssStupidDesires;
     2994                        else
     2995                            fAllowedRights = fAllowedRights
     2996                                           | PROCESS_VM_OPERATION
     2997                                           | PROCESS_VM_WRITE
     2998                                           | PROCESS_SET_INFORMATION
     2999                                           | PROCESS_SET_LIMITED_INFORMATION
     3000                                           | 0;
     3001                        pOpInfo->CallContext = NULL; /* don't assert this. */
     3002                    }
     3003                    pNtProtect->fFirstProcessCreateHandle = false;
     3004                }
     3005
     3006                /* Special case 3 on 8.1:
     3007                   The interaction between the CreateProcess code and CSRSS.EXE
     3008                   has changed to the better with Windows 8.1.  CSRSS.EXE no
     3009                   longer duplicates the process (thread too) handle, but opens
     3010                   it, thus allowing us to do our job. */
     3011                if (   g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 3)
     3012                    && pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed
     3013                    && pNtProtect->fCsrssFirstProcessCreateHandle
     3014                    && supdrvNtProtectIsAssociatedCsrss(pNtProtect, PsGetCurrentProcess())
     3015                   )
     3016                {
     3017                    pNtProtect->fCsrssFirstProcessCreateHandle = false;
     3018                    if (pOpInfo->Parameters->CreateHandleInformation.DesiredAccess == s_fCsrssStupidDesires)
     3019                    {
     3020                        /* Not needed: PROCESS_CREATE_THREAD, PROCESS_SET_SESSIONID,
     3021                           PROCESS_CREATE_PROCESS */
     3022                        fAllowedRights = fAllowedRights
     3023                                       | PROCESS_VM_OPERATION
     3024                                       | PROCESS_VM_WRITE
     3025                                       | PROCESS_DUP_HANDLE /* Needed for CreateProcess/VBoxTestOGL. */
     3026                                       | 0;
     3027                        pOpInfo->CallContext = NULL; /* don't assert this. */
     3028                    }
     3029                }
     3030
     3031                /* Special case 4, Windows 7, Vista, possibly 8, but not 8.1:
     3032                   The Themes service requires PROCESS_DUP_HANDLE access to our
     3033                   process or we won't get any menus and dialogs will be half
     3034                   unreadable.  This is _very_ unfortunate and more work will
     3035                   go into making this more secure.  */
     3036                if (   g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 0)
     3037                    && g_uNtVerCombined  < SUP_MAKE_NT_VER_SIMPLE(6, 2)
     3038                    && pOpInfo->Parameters->CreateHandleInformation.DesiredAccess == 0x1478 /* 6.1.7600.16385 (win7_rtm.090713-1255) */
     3039                    && pNtProtect->fThemesFirstProcessCreateHandle
     3040                    && supdrvNtProtectIsFrigginThemesService(pNtProtect, PsGetCurrentProcess()))
     3041                {
     3042                    pNtProtect->fThemesFirstProcessCreateHandle = true; /* Only once! */
     3043                    fAllowedRights |= PROCESS_DUP_HANDLE;
     3044                    pOpInfo->CallContext = NULL; /* don't assert this. */
     3045                }
     3046
     3047                Log(("vboxdrv/ProcessHandlePre: ctx=%04zx/%p wants %#x to %p/pid=%04zx [%d], allow %#x => %#x; %s\n",
     3048                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3049                     pOpInfo->Parameters->CreateHandleInformation.DesiredAccess,
     3050                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind, fAllowedRights,
     3051                     pOpInfo->Parameters->CreateHandleInformation.DesiredAccess & fAllowedRights,
     3052                     PsGetProcessImageFileName(PsGetCurrentProcess())));
     3053
     3054                pOpInfo->Parameters->CreateHandleInformation.DesiredAccess &= fAllowedRights;
     3055            }
     3056        }
     3057        else
     3058        {
     3059            /* Don't restrict the process accessing itself. */
     3060            if (   (PEPROCESS)pOpInfo->Object == PsGetCurrentProcess()
     3061                && pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess == pOpInfo->Object)
     3062            {
     3063                Log(("vboxdrv/ProcessHandlePre: ctx=%04zx/%p[%p] dup from %04zx/%p with %#x to %p in pid=%04zx [%d] %s\n",
     3064                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3065                     pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess,
     3066                     PsGetProcessId((PEPROCESS)pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess),
     3067                     pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess,
     3068                     pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess,
     3069                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind,
     3070                     PsGetProcessImageFileName(PsGetCurrentProcess()) ));
     3071
     3072                pOpInfo->CallContext = NULL; /* don't assert */
     3073            }
     3074            else
     3075            {
     3076                /* Special case 5 on Vista, 7 & 8:
     3077                   This is the CSRSS.EXE end of special case #1. */
     3078                if (   g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 3)
     3079                    && pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed
     3080                    && pNtProtect->fCsrssFirstProcessDuplicateHandle
     3081                    &&    pNtProtect->hParentPid
     3082                       == PsGetProcessId((PEPROCESS)pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess)
     3083                    && pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess == PsGetCurrentProcess()
     3084                    && supdrvNtProtectIsAssociatedCsrss(pNtProtect, PsGetCurrentProcess())
     3085                   )
     3086                {
     3087                    pNtProtect->fCsrssFirstProcessDuplicateHandle = false;
     3088                    if (pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess == s_fCsrssStupidDesires)
     3089                    {
     3090                        /* Not needed: PROCESS_CREATE_THREAD, PROCESS_SET_SESSIONID,
     3091                           PROCESS_CREATE_PROCESS, PROCESS_DUP_HANDLE */
     3092                        fAllowedRights = fAllowedRights
     3093                                       | PROCESS_VM_OPERATION
     3094                                       | PROCESS_VM_WRITE
     3095                                       | PROCESS_DUP_HANDLE /* Needed for launching VBoxTestOGL. */
     3096                                       | 0;
     3097                        pOpInfo->CallContext = NULL; /* don't assert this. */
     3098                    }
     3099                }
     3100
     3101                Log(("vboxdrv/ProcessHandlePre: ctx=%04zx/%p[%p] dup from %04zx/%p with %#x to %p in pid=%04zx [%d] %s\n",
     3102                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3103                     pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess,
     3104                     PsGetProcessId((PEPROCESS)pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess),
     3105                     pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess,
     3106                     pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess,
     3107                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind,
     3108                     PsGetProcessImageFileName(PsGetCurrentProcess()) ));
     3109
     3110                pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess &= fAllowedRights;
     3111            }
     3112        }
     3113        supdrvNtProtectRelease(pNtProtect);
     3114    }
     3115
     3116    return OB_PREOP_SUCCESS;
     3117}
     3118
     3119
     3120static VOID __stdcall
     3121supdrvNtProtectCallback_ProcessHandlePost(PVOID pvUser, POB_POST_OPERATION_INFORMATION pOpInfo)
     3122{
     3123    Assert(pvUser == NULL);
     3124    Assert(pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE || pOpInfo->Operation == OB_OPERATION_HANDLE_DUPLICATE);
     3125    Assert(pOpInfo->ObjectType == *PsProcessType);
     3126
     3127    if (   pOpInfo->CallContext
     3128        && NT_SUCCESS(pOpInfo->ReturnStatus))
     3129    {
     3130        ACCESS_MASK const fGrantedAccess = pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE
     3131                                         ? pOpInfo->Parameters->CreateHandleInformation.GrantedAccess
     3132                                         : pOpInfo->Parameters->DuplicateHandleInformation.GrantedAccess;
     3133        AssertReleaseMsg(   !(fGrantedAccess & ~(  SUPDRV_NT_ALLOW_PROCESS_RIGHTS
     3134                                                 | WRITE_OWNER | WRITE_DAC /* these two might be forced upon us */
     3135                                                 | PROCESS_UNKNOWN_4000 /* Seen set on win 8.1 */
     3136                                                 /*| PROCESS_UNKNOWN_8000 */ ) )
     3137                         || pOpInfo->KernelHandle,
     3138                         ("GrantedAccess=%#x - we allow %#x - we did not allow %#x\n",
     3139                          fGrantedAccess, SUPDRV_NT_ALLOW_PROCESS_RIGHTS, fGrantedAccess & ~SUPDRV_NT_ALLOW_PROCESS_RIGHTS));
     3140    }
     3141}
     3142
     3143# undef SUPDRV_NT_ALLOW_PROCESS_RIGHTS
     3144
     3145/** @} */
     3146
     3147
     3148/** @name Thread Handle Callbacks
     3149 * @{ */
     3150
     3151/* From ntifs.h */
     3152extern "C" NTKERNELAPI PEPROCESS __stdcall IoThreadToProcess(PETHREAD);
     3153
     3154/** Thread rights that we allow for handles to stub and VM processes. */
     3155# define SUPDRV_NT_ALLOWED_THREAD_RIGHTS  \
     3156    (  THREAD_TERMINATE \
     3157     | THREAD_GET_CONTEXT \
     3158     | THREAD_QUERY_INFORMATION \
     3159     | THREAD_QUERY_LIMITED_INFORMATION \
     3160     | DELETE \
     3161     | READ_CONTROL \
     3162     | SYNCHRONIZE)
     3163/** @todo consider THREAD_SET_LIMITED_INFORMATION & THREAD_RESUME */
     3164
     3165/** Evil thread rights.
     3166 * @remarks THREAD_RESUME is not included as it seems to be forced upon us by
     3167 *          Windows 8.1, at least for some processes.  We dont' actively
     3168 *          allow it though, just tollerate it when forced to. */
     3169# define SUPDRV_NT_EVIL_THREAD_RIGHTS  \
     3170    (  THREAD_SUSPEND_RESUME \
     3171     | THREAD_SET_CONTEXT \
     3172     | THREAD_SET_INFORMATION \
     3173     | THREAD_SET_LIMITED_INFORMATION /*?*/ \
     3174     | THREAD_SET_THREAD_TOKEN /*?*/ \
     3175     | THREAD_IMPERSONATE /*?*/ \
     3176     | THREAD_DIRECT_IMPERSONATION /*?*/ \
     3177     /*| THREAD_RESUME - see remarks. */ \
     3178     | 0)
     3179AssertCompile((SUPDRV_NT_EVIL_THREAD_RIGHTS & SUPDRV_NT_ALLOWED_THREAD_RIGHTS) == 0);
     3180
     3181
     3182static OB_PREOP_CALLBACK_STATUS __stdcall
     3183supdrvNtProtectCallback_ThreadHandlePre(PVOID pvUser, POB_PRE_OPERATION_INFORMATION pOpInfo)
     3184{
     3185    Assert(pvUser == NULL);
     3186    Assert(pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE || pOpInfo->Operation == OB_OPERATION_HANDLE_DUPLICATE);
     3187    Assert(pOpInfo->ObjectType == *PsThreadType);
     3188
     3189    PEPROCESS pProcess = IoThreadToProcess((PETHREAD)pOpInfo->Object);
     3190    PSUPDRVNTPROTECT pNtProtect = supdrvNtProtectLookup(PsGetProcessId(pProcess));
     3191    pOpInfo->CallContext = pNtProtect; /* Just for reference. */
     3192    if (pNtProtect)
     3193    {
     3194        static ACCESS_MASK const s_fCsrssStupidDesires = 0x1fffff;
     3195        ACCESS_MASK fAllowedRights = SUPDRV_NT_ALLOWED_THREAD_RIGHTS;
     3196
     3197        if (pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE)
     3198        {
     3199            /* Don't restrict the process accessing its own threads. */
     3200            if (pProcess == PsGetCurrentProcess())
     3201            {
     3202                Log(("vboxdrv/ThreadHandlePre: ctx=%04zx/%p wants %#x to %p in pid=%04zx [%d] self\n",
     3203                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3204                     pOpInfo->Parameters->CreateHandleInformation.DesiredAccess,
     3205                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind));
     3206                pOpInfo->CallContext = NULL; /* don't assert */
     3207                pNtProtect->fFirstThreadCreateHandle = false;
     3208            }
     3209            else
     3210            {
     3211                /* Special case 1 on Vista, 7, 8:
     3212                   The CreateProcess code passes the handle over to CSRSS.EXE
     3213                   and the code inBaseSrvCreateProcess will duplicate the
     3214                   handle with 0x1fffff as access mask.  NtDuplicateObject will
     3215                   fail this call before it ever gets down here.  */
     3216                if (   g_uNtVerCombined < SUP_MAKE_NT_VER_SIMPLE(6, 3)
     3217                    && pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed
     3218                    && pNtProtect->fFirstThreadCreateHandle
     3219                    && pNtProtect->hParentPid == PsGetProcessId(PsGetCurrentProcess()))
     3220                {
     3221                    if (   !pOpInfo->KernelHandle
     3222                        && pOpInfo->Parameters->CreateHandleInformation.DesiredAccess == s_fCsrssStupidDesires)
     3223                    {
     3224                        fAllowedRights |= s_fCsrssStupidDesires;
     3225                        pOpInfo->CallContext = NULL; /* don't assert this. */
     3226                    }
     3227                    pNtProtect->fFirstThreadCreateHandle = false;
     3228                }
     3229
     3230                /* Special case 2 on 8.1, possibly also Vista, 7, 8:
     3231                   When creating a process like VBoxTestOGL from the VM process,
     3232                   CSRSS.EXE will try talk to the calling thread and, it
     3233                   appears, impersonate it.  We unfortunately need to allow
     3234                   this or there will be no 3D support.  Typical DbgPrint:
     3235                        "SXS: BasepCreateActCtx() Calling csrss server failed. Status = 0xc00000a5" */
     3236                SUPDRVNTPROTECTKIND enmProcessKind;
     3237                if (   g_uNtVerCombined >= SUP_MAKE_NT_VER_COMBINED(6, 0, 0, 0, 0)
     3238                    && (   (enmProcessKind = pNtProtect->enmProcessKind) == kSupDrvNtProtectKind_VmProcessConfirmed
     3239                        || enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed)
     3240                    && supdrvNtProtectIsAssociatedCsrss(pNtProtect, PsGetCurrentProcess()) )
     3241                {
     3242                    fAllowedRights |= THREAD_IMPERSONATE;
     3243                    fAllowedRights |= THREAD_DIRECT_IMPERSONATION;
     3244                    //fAllowedRights |= THREAD_SET_LIMITED_INFORMATION; - try without this one
     3245                    pOpInfo->CallContext = NULL; /* don't assert this. */
     3246                }
     3247
     3248                Log(("vboxdrv/ThreadHandlePre: ctx=%04zx/%p wants %#x to %p in pid=%04zx [%d], allow %#x => %#x; %s\n",
     3249                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3250                     pOpInfo->Parameters->CreateHandleInformation.DesiredAccess,
     3251                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind, fAllowedRights,
     3252                     pOpInfo->Parameters->CreateHandleInformation.DesiredAccess & fAllowedRights,
     3253                     PsGetProcessImageFileName(PsGetCurrentProcess())));
     3254
     3255                pOpInfo->Parameters->CreateHandleInformation.DesiredAccess &= fAllowedRights;
     3256            }
     3257        }
     3258        else
     3259        {
     3260            /* Don't restrict the process accessing its own threads. */
     3261            if (   pProcess == PsGetCurrentProcess()
     3262                && (PEPROCESS)pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess == pProcess)
     3263            {
     3264                Log(("vboxdrv/ThreadHandlePre: ctx=%04zx/%p[%p] dup from %04zx/%p with %#x to %p in pid=%04zx [%d] self\n",
     3265                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3266                     pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess,
     3267                     PsGetProcessId((PEPROCESS)pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess),
     3268                     pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess,
     3269                     pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess,
     3270                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind,
     3271                     PsGetProcessImageFileName(PsGetCurrentProcess()) ));
     3272                pOpInfo->CallContext = NULL; /* don't assert */
     3273            }
     3274            else
     3275            {
     3276                /* Special case 3 on Vista, 7, 8:
     3277                   This is the follow up to special case 1. */
     3278                SUPDRVNTPROTECTKIND enmProcessKind;
     3279                if (   g_uNtVerCombined >= SUP_MAKE_NT_VER_COMBINED(6, 0, 0, 0, 0)
     3280                    && (   (enmProcessKind = pNtProtect->enmProcessKind) == kSupDrvNtProtectKind_VmProcessConfirmed
     3281                        || enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed)
     3282                    && pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess == PsGetCurrentProcess()
     3283                    && supdrvNtProtectIsAssociatedCsrss(pNtProtect, PsGetCurrentProcess()) )
     3284                {
     3285                    fAllowedRights |= THREAD_IMPERSONATE;
     3286                    fAllowedRights |= THREAD_DIRECT_IMPERSONATION;
     3287                    //fAllowedRights |= THREAD_SET_LIMITED_INFORMATION; - try without this one
     3288                    pOpInfo->CallContext = NULL; /* don't assert this. */
     3289                }
     3290
     3291                Log(("vboxdrv/ThreadHandlePre: ctx=%04zx/%p[%p] dup from %04zx/%p with %#x to %p in pid=%04zx [%d], allow %#x => %#x; %s\n",
     3292                     PsGetProcessId(PsGetCurrentProcess()), PsGetCurrentProcess(),
     3293                     pOpInfo->Parameters->DuplicateHandleInformation.TargetProcess,
     3294                     PsGetProcessId((PEPROCESS)pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess),
     3295                     pOpInfo->Parameters->DuplicateHandleInformation.SourceProcess,
     3296                     pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess,
     3297                     pOpInfo->Object, pNtProtect->AvlCore.Key, pNtProtect->enmProcessKind, fAllowedRights,
     3298                     pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess & fAllowedRights,
     3299                     PsGetProcessImageFileName(PsGetCurrentProcess()) ));
     3300
     3301                pOpInfo->Parameters->DuplicateHandleInformation.DesiredAccess &= fAllowedRights;
     3302            }
     3303        }
     3304
     3305        supdrvNtProtectRelease(pNtProtect);
     3306    }
     3307
     3308    return OB_PREOP_SUCCESS;
     3309}
     3310
     3311
     3312static VOID __stdcall
     3313supdrvNtProtectCallback_ThreadHandlePost(PVOID pvUser, POB_POST_OPERATION_INFORMATION pOpInfo)
     3314{
     3315    Assert(pvUser == NULL);
     3316    Assert(pOpInfo->Operation == OB_OPERATION_HANDLE_CREATE || pOpInfo->Operation == OB_OPERATION_HANDLE_DUPLICATE);
     3317    Assert(pOpInfo->ObjectType == *PsThreadType);
     3318
     3319    if (   pOpInfo->CallContext
     3320        && NT_SUCCESS(pOpInfo->ReturnStatus))
     3321    {
     3322        ACCESS_MASK const fGrantedAccess = pOpInfo->Parameters->CreateHandleInformation.GrantedAccess;
     3323        AssertReleaseMsg(   !(fGrantedAccess & ~(  SUPDRV_NT_ALLOWED_THREAD_RIGHTS
     3324                                                 | WRITE_OWNER | WRITE_DAC /* these two might be forced upon us */
     3325                                                 | THREAD_RESUME /* This seems to be force upon us too with 8.1. */
     3326                                                 ) )
     3327                         || pOpInfo->KernelHandle,
     3328                         ("GrantedAccess=%#x - we allow %#x - we did not allow %#x\n",
     3329                          fGrantedAccess, SUPDRV_NT_ALLOWED_THREAD_RIGHTS, fGrantedAccess & ~SUPDRV_NT_ALLOWED_THREAD_RIGHTS));
     3330    }
     3331}
     3332
     3333# undef SUPDRV_NT_ALLOWED_THREAD_RIGHTS
     3334
     3335/** @} */
     3336
     3337
     3338/**
     3339 * Creates a new process protection structure.
     3340 *
     3341 * @returns VBox status code.
     3342 * @param   ppNtProtect         Where to return the pointer to the structure
     3343 *                              on success.
     3344 * @param   hPid                The process ID of the process to protect.
     3345 * @param   enmProcessKind      The kind of process we're protecting.
     3346 * @param   fLink               Whether to link the structure into the tree.
     3347 */
     3348static int supdrvNtProtectCreate(PSUPDRVNTPROTECT *ppNtProtect, HANDLE hPid, SUPDRVNTPROTECTKIND enmProcessKind, bool fLink)
     3349{
     3350    AssertReturn(g_hNtProtectLock != NIL_RTSPINLOCK, VERR_WRONG_ORDER);
     3351
     3352    PSUPDRVNTPROTECT pNtProtect = (PSUPDRVNTPROTECT)RTMemAllocZ(sizeof(*pNtProtect));
     3353    if (!pNtProtect)
     3354        return VERR_NO_MEMORY;
     3355
     3356    pNtProtect->AvlCore.Key                  = hPid;
     3357    pNtProtect->u32Magic                     = SUPDRVNTPROTECT_MAGIC;
     3358    pNtProtect->cRefs                        = 1;
     3359    pNtProtect->enmProcessKind               = enmProcessKind;
     3360    pNtProtect->hParentPid                   = NULL;
     3361    pNtProtect->hCsrssPid                    = NULL;
     3362    pNtProtect->pCsrssProcess                = NULL;
     3363
     3364    if (fLink)
     3365    {
     3366        RTSpinlockAcquire(g_hNtProtectLock);
     3367        bool fSuccess = RTAvlPVInsert(&g_NtProtectTree, &pNtProtect->AvlCore);
     3368        RTSpinlockRelease(g_hNtProtectLock);
     3369
     3370        if (!fSuccess)
     3371        {
     3372            /* Duplicate entry, fail. */
     3373            pNtProtect->u32Magic = SUPDRVNTPROTECT_MAGIC_DEAD;
     3374            RTMemFree(pNtProtect);
     3375            return VERR_ACCESS_DENIED;
     3376        }
     3377    }
     3378
     3379    *ppNtProtect = pNtProtect;
     3380    return VINF_SUCCESS;
     3381}
     3382
     3383
     3384/**
     3385 * Releases a reference to a NT protection structure.
     3386 *
     3387 * @param   pNtProtect          The NT protection structure.
     3388 */
     3389static void supdrvNtProtectRelease(PSUPDRVNTPROTECT pNtProtect)
     3390{
     3391    if (!pNtProtect)
     3392        return;
     3393    AssertReturnVoid(pNtProtect->u32Magic == SUPDRVNTPROTECT_MAGIC);
     3394
     3395    RTSpinlockAcquire(g_hNtProtectLock);
     3396    uint32_t cRefs = ASMAtomicDecU32(&pNtProtect->cRefs);
     3397    if (cRefs != 0)
     3398        RTSpinlockRelease(g_hNtProtectLock);
     3399    else
     3400    {
     3401        /*
     3402         * That was the last reference.  Remove it from the tree, invalidate it
     3403         * and free the resources associated with it.  Also, release any
     3404         * child/parent references related to this protection structure.
     3405         */
     3406        ASMAtomicWriteU32(&pNtProtect->u32Magic, SUPDRVNTPROTECT_MAGIC_DEAD);
     3407        PSUPDRVNTPROTECT pRemoved = (PSUPDRVNTPROTECT)RTAvlPVRemove(&g_NtProtectTree, pNtProtect->AvlCore.Key);
     3408
     3409        PSUPDRVNTPROTECT pRemovedChild = NULL;
     3410        PSUPDRVNTPROTECT pChild = NULL;
     3411        if (pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubParent)
     3412        {
     3413            pChild = pNtProtect->u.pChild;
     3414            if (pChild)
     3415            {
     3416                pNtProtect->u.pChild   = NULL;
     3417                pChild->u.pParent      = NULL;
     3418                pChild->enmProcessKind = kSupDrvNtProtectKind_VmProcessDead;
     3419                uint32_t cChildRefs = ASMAtomicIncU32(&pChild->cRefs);
     3420                if (!cChildRefs)
     3421                    pRemovedChild = (PSUPDRVNTPROTECT)RTAvlPVRemove(&g_NtProtectTree, pChild->AvlCore.Key);
     3422                else
     3423                    pChild = NULL;
     3424            }
     3425        }
     3426        else
     3427            AssertRelease(pNtProtect->enmProcessKind != kSupDrvNtProtectKind_VmProcessUnconfirmed);
     3428
     3429        RTSpinlockRelease(g_hNtProtectLock);
     3430        Assert(pRemoved == pNtProtect);
     3431        Assert(pRemovedChild == pChild);
     3432
     3433        if (pNtProtect->pCsrssProcess)
     3434        {
     3435            ObDereferenceObject(pNtProtect->pCsrssProcess);
     3436            pNtProtect->pCsrssProcess = NULL;
     3437        }
     3438
     3439        RTMemFree(pNtProtect);
     3440        if (pChild)
     3441            RTMemFree(pChild);
     3442    }
     3443}
     3444
     3445
     3446/**
     3447 * Looks up a PID in the NT protect tree.
     3448 *
     3449 * @returns Pointer to a NT protection structure (with a referenced) on success,
     3450 *          NULL if not found.
     3451 * @param   hPid                The process ID.
     3452 */
     3453static PSUPDRVNTPROTECT supdrvNtProtectLookup(HANDLE hPid)
     3454{
     3455    RTSpinlockAcquire(g_hNtProtectLock);
     3456    PSUPDRVNTPROTECT pFound = (PSUPDRVNTPROTECT)RTAvlPVGet(&g_NtProtectTree, hPid);
     3457    if (pFound)
     3458        ASMAtomicIncU32(&pFound->cRefs);
     3459    RTSpinlockRelease(g_hNtProtectLock);
     3460    return pFound;
     3461}
     3462
     3463
     3464/**
     3465 * Worker for supdrvNtProtectVerifyProcess that verifies the handles to a VM
     3466 * process and its thread.
     3467 *
     3468 * @returns VBox status code.
     3469 * @param   pNtProtect          The NT protect structure for getting information
     3470 *                              about special processes.
     3471 */
     3472static int supdrvNtProtectRestrictHandlesToProcessAndThread(PSUPDRVNTPROTECT pNtProtect)
     3473{
     3474    /*
     3475     * What to protect.
     3476     */
     3477    PEPROCESS   pProtectedProcess = PsGetCurrentProcess();
     3478    HANDLE      hProtectedPid     = PsGetProcessId(pProtectedProcess);
     3479    PETHREAD    pProtectedThread  = PsGetCurrentThread();
     3480    AssertReturn(pNtProtect->AvlCore.Key == hProtectedPid, VERR_INTERNAL_ERROR_5);
     3481
     3482    /*
     3483     * Take a snapshot of all the handles in the system.
     3484     */
     3485    uint32_t    cbBuf    = _256K;
     3486    uint8_t    *pbBuf    = (uint8_t *)RTMemAlloc(cbBuf);
     3487    ULONG       cbNeeded = cbBuf;
     3488    NTSTATUS rcNt = NtQuerySystemInformation(SystemExtendedHandleInformation, pbBuf, cbBuf, &cbNeeded);
     3489    if (!NT_SUCCESS(rcNt))
     3490    {
     3491        while (   rcNt == STATUS_INFO_LENGTH_MISMATCH
     3492               && cbNeeded > cbBuf
     3493               && cbBuf <= 32U*_1M)
     3494        {
     3495            cbBuf = RT_ALIGN_32(cbNeeded + _4K, _64K);
     3496            RTMemFree(pbBuf);
     3497            pbBuf = (uint8_t *)RTMemAlloc(cbBuf);
     3498            if (!pbBuf)
     3499                return VERR_NO_MEMORY;
     3500            rcNt = NtQuerySystemInformation(SystemExtendedHandleInformation, pbBuf, cbBuf, &cbNeeded);
     3501        }
     3502        if (!NT_SUCCESS(rcNt))
     3503        {
     3504            RTMemFree(pbBuf);
     3505            return RTErrConvertFromNtStatus(rcNt);
     3506        }
     3507    }
     3508
     3509    /*
     3510     * Walk the information and look for handles to the two objects we're protecting.
     3511     */
     3512    int rc = VINF_SUCCESS;
     3513
     3514    uint32_t cCsrssProcessHandles  = 0;
     3515    uint32_t cSystemProcessHandles = 0;
     3516    uint32_t cEvilProcessHandles   = 0;
     3517    uint32_t cBenignProcessHandles = 0;
     3518
     3519    uint32_t cCsrssThreadHandles   = 0;
     3520    uint32_t cEvilThreadHandles    = 0;
     3521    uint32_t cBenignThreadHandles  = 0;
     3522
     3523    SYSTEM_HANDLE_INFORMATION_EX const *pInfo = (SYSTEM_HANDLE_INFORMATION_EX const *)pbBuf;
     3524    ULONG_PTR i = pInfo->NumberOfHandles;
     3525    AssertRelease(RT_OFFSETOF(SYSTEM_HANDLE_INFORMATION_EX, Handles[i]) == cbNeeded);
     3526    while (i-- > 0)
     3527    {
     3528        const char *pszType;
     3529        SYSTEM_HANDLE_ENTRY_INFO_EX const *pHandleInfo = &pInfo->Handles[i];
     3530        if (pHandleInfo->Object == pProtectedProcess)
     3531        {
     3532            /* Handles within the protected process is fine. */
     3533            if (   !(pHandleInfo->GrantedAccess & SUPDRV_NT_EVIL_PROCESS_RIGHTS)
     3534                || pHandleInfo->UniqueProcessId == hProtectedPid)
     3535            {
     3536                cBenignProcessHandles++;
     3537                continue;
     3538            }
     3539
     3540            /* CSRSS is allowed to have one evil process handle.
     3541               See the special cases in the hook code. */
     3542            if (   cCsrssProcessHandles < 1
     3543                && pHandleInfo->UniqueProcessId == pNtProtect->hCsrssPid)
     3544            {
     3545                cCsrssProcessHandles++;
     3546                continue;
     3547            }
     3548
     3549            /* The system process is allowed having one open process handle in
     3550               Windows 8.1 and later. */
     3551            if (   g_uNtVerCombined >= SUP_MAKE_NT_VER_SIMPLE(6, 3)
     3552                && cSystemProcessHandles < 1
     3553                && pHandleInfo->UniqueProcessId == PsGetProcessId(PsInitialSystemProcess))
     3554            {
     3555                cSystemProcessHandles++;
     3556                continue;
     3557            }
     3558
     3559            cEvilProcessHandles++;
     3560            pszType = "process";
     3561        }
     3562        else if (pHandleInfo->Object == pProtectedThread)
     3563        {
     3564            /* Handles within the protected process is fine. */
     3565            if (   !(pHandleInfo->GrantedAccess & SUPDRV_NT_EVIL_THREAD_RIGHTS)
     3566                || pHandleInfo->UniqueProcessId == hProtectedPid)
     3567            {
     3568                cBenignThreadHandles++;
     3569                continue;
     3570            }
     3571
     3572            /* CSRSS is allowed to have one evil handle to the primary thread
     3573               for LPC purposes.  See the hook for special case. */
     3574            if (   cCsrssThreadHandles < 1
     3575                && pHandleInfo->UniqueProcessId == pNtProtect->hCsrssPid)
     3576            {
     3577                cCsrssThreadHandles++;
     3578                continue;
     3579            }
     3580
     3581            cEvilThreadHandles++;
     3582            pszType = "thread";
     3583        }
     3584        else
     3585            continue;
     3586
     3587        /* Found evil handle. Currently ignoring on pre-Vista. */
     3588# ifndef VBOX_WITH_VISTA_NO_SP
     3589        if (   g_uNtVerCombined >= SUP_NT_VER_VISTA
     3590# else
     3591        if (   g_uNtVerCombined >= SUP_MAKE_NT_VER_COMBINED(6, 0, 6001, 0, 0)
     3592# endif
     3593            || g_pfnObRegisterCallbacks)
     3594        {
     3595            LogRel(("vboxdrv: Found evil handle to budding VM process: pid=%p h=%p acc=%#x attr=%#x type=%s\n",
     3596                    pHandleInfo->UniqueProcessId, pHandleInfo->HandleValue,
     3597                    pHandleInfo->GrantedAccess, pHandleInfo->HandleAttributes, pszType));
     3598            rc = VERR_SUPDRV_HARDENING_EVIL_HANDLE;
     3599        }
     3600    }
     3601
     3602    return rc;
     3603}
     3604
     3605
     3606/**
     3607 * Checks if the current process checks out as a VM process stub.
     3608 *
     3609 * @returns VBox status code.
     3610 * @param   pNtProtect          The NT protect structure.  This is upgraded to a
     3611 *                              final protection kind (state) on success.
     3612 */
     3613static int supdrvNtProtectVerifyProcess(PSUPDRVNTPROTECT pNtProtect)
     3614{
     3615    AssertReturn(PsGetProcessId(PsGetCurrentProcess()) == pNtProtect->AvlCore.Key, VERR_INTERNAL_ERROR_3);
     3616
     3617    /*
     3618     * Do the verification.  The handle restriction checks are only preformed
     3619     * on VM processes.
     3620     */
     3621    int rc = VINF_SUCCESS;
     3622    if (pNtProtect->enmProcessKind >= kSupDrvNtProtectKind_VmProcessUnconfirmed)
     3623        rc = supdrvNtProtectRestrictHandlesToProcessAndThread(pNtProtect);
     3624    if (RT_SUCCESS(rc))
     3625    {
     3626        char szErr[256];
     3627        RT_ZERO(szErr);
     3628        RTERRINFO ErrInfo;
     3629        RTErrInfoInit(&ErrInfo, szErr, sizeof(szErr));
     3630
     3631        rc = supHardenedWinVerifyProcess(NtCurrentProcess(), NtCurrentThread(), &ErrInfo);
     3632        if (RT_FAILURE(rc))
     3633            RTLogWriteDebugger(szErr, strlen(szErr));
     3634    }
     3635
     3636    /*
     3637     * Upgrade and return.
     3638     */
     3639    RTSpinlockAcquire(g_hNtProtectLock);
     3640
     3641    /* Stub process verficiation is pretty much straight forward. */
     3642    if (pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubUnverified)
     3643        pNtProtect->enmProcessKind = RT_SUCCESS(rc) ? kSupDrvNtProtectKind_StubSpawning : kSupDrvNtProtectKind_StubDead;
     3644
     3645    /* The VM process verification is a little bit more complicated
     3646       because we need to drop the parent process reference as well. */
     3647    else if (pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessUnconfirmed)
     3648    {
     3649        AssertRelease(pNtProtect->cRefs >= 2); /* Parent + Caller */
     3650        PSUPDRVNTPROTECT pParent = pNtProtect->u.pParent;
     3651        AssertRelease(pParent);
     3652        AssertRelease(pParent->u.pParent == pNtProtect);
     3653        AssertRelease(pParent->enmProcessKind == kSupDrvNtProtectKind_StubParent);
     3654        pParent->u.pParent = NULL;
     3655
     3656        pNtProtect->u.pParent = NULL;
     3657        ASMAtomicDecU32(&pNtProtect->cRefs);
     3658
     3659        if (RT_SUCCESS(rc))
     3660            pNtProtect->enmProcessKind = kSupDrvNtProtectKind_VmProcessConfirmed;
     3661        else
     3662            pNtProtect->enmProcessKind = kSupDrvNtProtectKind_VmProcessDead;
     3663    }
     3664
     3665    /* Since the stub and VM processes are only supposed to have one thread,
     3666       we're not supposed to be subject to any races from within the processes.
     3667
     3668       There is a race between VM process verification and the stub process
     3669       exiting, though.  We require the stub process to be alive until the new
     3670       VM process has made it thru the validation.  So, when the stub
     3671       terminates the notification handler will change the state of both stub
     3672       and VM process to dead.
     3673
     3674       Also, I'm not entirely certain where the process
     3675       termination notification is triggered from, so that can theorically
     3676       create a race in both cases.  */
     3677    else
     3678    {
     3679        AssertReleaseMsg(   pNtProtect->enmProcessKind == kSupDrvNtProtectKind_StubDead
     3680                         || pNtProtect->enmProcessKind == kSupDrvNtProtectKind_VmProcessDead,
     3681                         ("enmProcessKind=%d rc=%Rrc\n", pNtProtect->enmProcessKind, rc));
     3682        if (RT_SUCCESS(rc))
     3683            rc = VERR_INVALID_STATE; /* There should be no races here. */
     3684    }
     3685
     3686    RTSpinlockRelease(g_hNtProtectLock);
     3687    return rc;
     3688}
     3689
     3690
     3691# ifndef VBOX_WITHOUT_DEBUGGER_CHECKS
     3692
     3693/**
     3694 * Checks if the current process is being debugged.
     3695 * @return @c true if debugged, @c false if not.
     3696 */
     3697static bool supdrvNtIsDebuggerAttached(void)
     3698{
     3699    return PsIsProcessBeingDebugged(PsGetCurrentProcess()) != FALSE;
     3700}
     3701
     3702# endif /* !VBOX_WITHOUT_DEBUGGER_CHECKS */
     3703
     3704
     3705/**
     3706 * Terminates the hardening bits.
     3707 */
     3708static void supdrvNtProtectTerm(void)
     3709{
     3710    /*
     3711     * Stop intercepting process and thread handle creation calls.
     3712     */
     3713    if (g_pvObCallbacksCookie)
     3714    {
     3715        g_pfnObUnRegisterCallbacks(g_pvObCallbacksCookie);
     3716        g_pvObCallbacksCookie = NULL;
     3717    }
     3718
     3719    /*
     3720     * Stop intercepting process creation and termination notifications.
     3721     */
     3722    NTSTATUS rcNt;
     3723    if (g_pfnPsSetCreateProcessNotifyRoutineEx)
     3724        rcNt = g_pfnPsSetCreateProcessNotifyRoutineEx(supdrvNtProtectCallback_ProcessCreateNotifyEx, TRUE /*fRemove*/);
     3725    else
     3726        rcNt = PsSetCreateProcessNotifyRoutine(supdrvNtProtectCallback_ProcessCreateNotify, TRUE /*fRemove*/);
     3727    AssertMsg(NT_SUCCESS(rcNt), ("rcNt=%#x\n", rcNt));
     3728
     3729    Assert(g_NtProtectTree == NULL);
     3730
     3731    /*
     3732     * Clean up globals.
     3733     */
     3734    RTSpinlockDestroy(g_hNtProtectLock);
     3735    g_NtProtectTree = NIL_RTSPINLOCK;
     3736
     3737    supHardenedWinTermImageVerifier();
     3738}
     3739
     3740# ifdef RT_ARCH_X86
     3741DECLASM(void) supdrvNtQueryVirtualMemory_0xAF(void);
     3742DECLASM(void) supdrvNtQueryVirtualMemory_0xB0(void);
     3743DECLASM(void) supdrvNtQueryVirtualMemory_0xB1(void);
     3744DECLASM(void) supdrvNtQueryVirtualMemory_0xB2(void);
     3745DECLASM(void) supdrvNtQueryVirtualMemory_0xB3(void);
     3746DECLASM(void) supdrvNtQueryVirtualMemory_0xB4(void);
     3747DECLASM(void) supdrvNtQueryVirtualMemory_0xB5(void);
     3748DECLASM(void) supdrvNtQueryVirtualMemory_0xB6(void);
     3749DECLASM(void) supdrvNtQueryVirtualMemory_0xB7(void);
     3750DECLASM(void) supdrvNtQueryVirtualMemory_0xB8(void);
     3751DECLASM(void) supdrvNtQueryVirtualMemory_0xB9(void);
     3752DECLASM(void) supdrvNtQueryVirtualMemory_0xBA(void);
     3753DECLASM(void) supdrvNtQueryVirtualMemory_0xBB(void);
     3754DECLASM(void) supdrvNtQueryVirtualMemory_0xBC(void);
     3755DECLASM(void) supdrvNtQueryVirtualMemory_0xBD(void);
     3756DECLASM(void) supdrvNtQueryVirtualMemory_0xBE(void);
     3757# elif defined(RT_ARCH_AMD64)
     3758DECLASM(void) supdrvNtQueryVirtualMemory_0x1F(void);
     3759DECLASM(void) supdrvNtQueryVirtualMemory_0x20(void);
     3760DECLASM(void) supdrvNtQueryVirtualMemory_0x21(void);
     3761DECLASM(void) supdrvNtQueryVirtualMemory_0x22(void);
     3762DECLASM(void) supdrvNtQueryVirtualMemory_0x23(void);
     3763extern "C" NTSYSAPI NTSTATUS NTAPI ZwRequestWaitReplyPort(HANDLE, PVOID, PVOID);
     3764# endif
     3765
     3766/**
     3767 * Initalizes the hardening bits.
     3768 *
     3769 * @returns NT status code.
     3770 */
     3771static NTSTATUS supdrvNtProtectInit(void)
     3772{
     3773    /*
     3774     * Initialize the globals.
     3775     */
     3776
     3777    /* The NT version. */
     3778    ULONG uMajor, uMinor, uBuild;
     3779    PsGetVersion(&uMajor, &uMinor, &uBuild, NULL);
     3780    g_uNtVerCombined = SUP_MAKE_NT_VER_COMBINED(uMajor, uMinor, uBuild, 0, 0);
     3781
     3782    /* Resolve methods we want but isn't available everywhere. */
     3783    UNICODE_STRING RoutineName;
     3784
     3785    RtlInitUnicodeString(&RoutineName, L"ObRegisterCallbacks");
     3786    g_pfnObRegisterCallbacks   = (PFNOBREGISTERCALLBACKS)MmGetSystemRoutineAddress(&RoutineName);
     3787
     3788    RtlInitUnicodeString(&RoutineName, L"ObUnRegisterCallbacks");
     3789    g_pfnObUnRegisterCallbacks = (PFNOBUNREGISTERCALLBACKS)MmGetSystemRoutineAddress(&RoutineName);
     3790
     3791    RtlInitUnicodeString(&RoutineName, L"PsSetCreateProcessNotifyRoutineEx");
     3792    g_pfnPsSetCreateProcessNotifyRoutineEx = (PFNPSSETCREATEPROCESSNOTIFYROUTINEEX)MmGetSystemRoutineAddress(&RoutineName);
     3793
     3794    RtlInitUnicodeString(&RoutineName, L"PsReferenceProcessFilePointer");
     3795    g_pfnPsReferenceProcessFilePointer = (PFNPSREFERENCEPROCESSFILEPOINTER)MmGetSystemRoutineAddress(&RoutineName);
     3796
     3797    RtlInitUnicodeString(&RoutineName, L"PsIsProtectedProcessLight");
     3798    g_pfnPsIsProtectedProcessLight = (PFNPSISPROTECTEDPROCESSLIGHT)MmGetSystemRoutineAddress(&RoutineName);
     3799
     3800    RtlInitUnicodeString(&RoutineName, L"ZwQueryVirtualMemory"); /* Yes, using Zw version here. */
     3801    g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)MmGetSystemRoutineAddress(&RoutineName);
     3802    if (!g_pfnNtQueryVirtualMemory && g_uNtVerCombined < SUP_NT_VER_VISTA)
     3803    {
     3804        /* XP & W2K3 doesn't have this function exported, so we've cooked up a
     3805           few alternative in the assembly helper file that uses the code in
     3806           ZwQueryVolumeInformationFile with a different eax value. */
     3807# ifdef RT_ARCH_X86
     3808        uint8_t const *pbCode = (uint8_t const *)(uintptr_t)ZwQueryVolumeInformationFile;
     3809        if (*pbCode == 0xb8) /* mov eax, dword */
     3810            switch (*(uint32_t const *)&pbCode[1])
     3811            {
     3812                case 0xb0: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xAF; break; /* just in case */
     3813                case 0xb1: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB0; break; /* just in case */
     3814                case 0xb2: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB1; break; /* just in case */
     3815                case 0xb3: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB2; break; /* XP SP3 */
     3816                case 0xb4: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB2; break; /* just in case */
     3817                case 0xb5: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB3; break; /* just in case */
     3818                case 0xb6: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB4; break; /* just in case */
     3819                case 0xb7: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB5; break; /* just in case */
     3820                case 0xb8: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB6; break; /* just in case */
     3821                case 0xb9: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB7; break; /* just in case */
     3822                case 0xba: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xB8; break; /* just in case */
     3823                case 0xbb: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xBA; break; /* W2K3 R2 SP2 */
     3824                case 0xbc: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xBB; break; /* just in case */
     3825                case 0xbd: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xBC; break; /* just in case */
     3826                case 0xbe: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xBD; break; /* just in case */
     3827                case 0xbf: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0xBE; break; /* just in case */
     3828            }
     3829# elif defined(RT_ARCH_AMD64)
     3830        uint8_t const *pbCode = (uint8_t const *)(uintptr_t)ZwRequestWaitReplyPort;
     3831        if (   pbCode[ 0] == 0x48   /* mov rax, rsp */
     3832            && pbCode[ 1] == 0x8b
     3833            && pbCode[ 2] == 0xc4
     3834            && pbCode[ 3] == 0xfa   /* cli */
     3835            && pbCode[ 4] == 0x48   /* sub rsp, 10h */
     3836            && pbCode[ 5] == 0x83
     3837            && pbCode[ 6] == 0xec
     3838            && pbCode[ 7] == 0x10
     3839            && pbCode[ 8] == 0x50   /* push rax */
     3840            && pbCode[ 9] == 0x9c   /* pushfq */
     3841            && pbCode[10] == 0x6a   /* push 10 */
     3842            && pbCode[11] == 0x10
     3843            && pbCode[12] == 0x48   /* lea rax, [nt!KiServiceLinkage] */
     3844            && pbCode[13] == 0x8d
     3845            && pbCode[14] == 0x05
     3846            && pbCode[19] == 0x50   /* push rax */
     3847            && pbCode[20] == 0xb8   /* mov eax,1fh <- the syscall no. */
     3848            /*&& pbCode[21] == 0x1f*/
     3849            && pbCode[22] == 0x00
     3850            && pbCode[23] == 0x00
     3851            && pbCode[24] == 0x00
     3852            && pbCode[25] == 0xe9   /* jmp KiServiceInternal */
     3853           )
     3854        {
     3855            uint8_t const *pbKiServiceInternal = &pbCode[30] + *(int32_t const *)&pbCode[26];
     3856            uint8_t const *pbKiServiceLinkage  = &pbCode[19] + *(int32_t const *)&pbCode[15];
     3857            if (*pbKiServiceLinkage == 0xc3)
     3858            {
     3859                g_pfnKiServiceInternal = (PFNRT)pbKiServiceInternal;
     3860                g_pfnKiServiceLinkage  = (PFNRT)pbKiServiceLinkage;
     3861                switch (pbCode[21])
     3862                {
     3863                    case 0x1e: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0x1F; break;
     3864                    case 0x1f: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0x20; break;
     3865                    case 0x20: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0x21; break;
     3866                    case 0x21: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0x22; break;
     3867                    case 0x22: g_pfnNtQueryVirtualMemory = (PFNNTQUERYVIRTUALMEMORY)supdrvNtQueryVirtualMemory_0x23; break;
     3868                }
     3869            }
     3870        }
     3871# endif
     3872    }
     3873    if (!g_pfnNtQueryVirtualMemory)
     3874    {
     3875        LogRel(("vboxdrv: Cannot locate ZwQueryVirtualMemory in ntoskrnl, nor were we able to cook up a replacement.\n"));
     3876        return STATUS_PROCEDURE_NOT_FOUND;
     3877    }
     3878
     3879
     3880    /* The spinlock protecting our structures. */
     3881    int rc = RTSpinlockCreate(&g_hNtProtectLock, RTSPINLOCK_FLAGS_INTERRUPT_UNSAFE, "NtProtectLock");
     3882    if (RT_FAILURE(rc))
     3883        return VBoxDrvNtErr2NtStatus(rc);
     3884    g_NtProtectTree = NULL;
     3885
     3886    /* Image stuff + certificates. */
     3887    NTSTATUS rcNt;
     3888    rc = supHardenedWinInitImageVerifier(NULL);
     3889    if (RT_SUCCESS(rc))
     3890    {
     3891        /*
     3892         * Intercept process creation and termination.
     3893         */
     3894        if (g_pfnPsSetCreateProcessNotifyRoutineEx)
     3895            rcNt = g_pfnPsSetCreateProcessNotifyRoutineEx(supdrvNtProtectCallback_ProcessCreateNotifyEx, FALSE /*fRemove*/);
     3896        else
     3897            rcNt = PsSetCreateProcessNotifyRoutine(supdrvNtProtectCallback_ProcessCreateNotify, FALSE /*fRemove*/);
     3898        if (NT_SUCCESS(rcNt))
     3899        {
     3900            /*
     3901             * Intercept process and thread handle creation calls.
     3902             * The preferred method is only available on Vista SP1+.
     3903             */
     3904            if (g_pfnObRegisterCallbacks && g_pfnObUnRegisterCallbacks)
     3905            {
     3906                static OB_OPERATION_REGISTRATION s_aObOperations[] =
     3907                {
     3908                    {
     3909                        PsProcessType,
     3910                        OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE,
     3911                        supdrvNtProtectCallback_ProcessHandlePre,
     3912                        supdrvNtProtectCallback_ProcessHandlePost,
     3913                    },
     3914                    {
     3915                        PsThreadType,
     3916                        OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE,
     3917                        supdrvNtProtectCallback_ThreadHandlePre,
     3918                        supdrvNtProtectCallback_ThreadHandlePost,
     3919                    },
     3920                };
     3921                static OB_CALLBACK_REGISTRATION s_ObCallbackReg =
     3922                {
     3923                    /* .Version                     = */ OB_FLT_REGISTRATION_VERSION,
     3924                    /* .OperationRegistrationCount  = */ RT_ELEMENTS(s_aObOperations),
     3925                    /* .Altitude.Length             = */ 0,
     3926                    /* .Altitude.MaximumLength      = */ 0,
     3927                    /* .Altitude.Buffer             = */ NULL,
     3928                    /* .RegistrationContext         = */ NULL,
     3929                    /* .OperationRegistration       = */ &s_aObOperations[0]
     3930                };
     3931                static WCHAR const *s_apwszAltitudes[] = /** @todo get a valid number */
     3932                {
     3933                     L"48596.98940",  L"46935.19485",  L"49739.39704",  L"40334.74976",
     3934                     L"66667.98940",  L"69888.19485",  L"69889.39704",  L"60364.74976",
     3935                     L"85780.98940",  L"88978.19485",  L"89939.39704",  L"80320.74976",
     3936                     L"329879.98940", L"326787.19485", L"328915.39704", L"320314.74976",
     3937                };
     3938
     3939                rcNt = STATUS_FLT_INSTANCE_ALTITUDE_COLLISION;
     3940                for (uint32_t i = 0; i < RT_ELEMENTS(s_apwszAltitudes) && rcNt == STATUS_FLT_INSTANCE_ALTITUDE_COLLISION; i++)
     3941                {
     3942                    s_ObCallbackReg.Altitude.Buffer = (WCHAR *)s_apwszAltitudes[i];
     3943                    s_ObCallbackReg.Altitude.Length = (uint16_t)RTUtf16Len(s_apwszAltitudes[i]) * sizeof(WCHAR);
     3944                    s_ObCallbackReg.Altitude.MaximumLength = s_ObCallbackReg.Altitude.Length + sizeof(WCHAR);
     3945
     3946                    rcNt = g_pfnObRegisterCallbacks(&s_ObCallbackReg, &g_pvObCallbacksCookie);
     3947                    if (NT_SUCCESS(rcNt))
     3948                    {
     3949                        /*
     3950                         * Happy ending.
     3951                         */
     3952                        return STATUS_SUCCESS;
     3953                    }
     3954                }
     3955                LogRel(("vboxdrv: ObRegisterCallbacks failed with rcNt=%#x\n", rcNt));
     3956                g_pvObCallbacksCookie = NULL;
     3957            }
     3958            else
     3959            {
     3960                /*
     3961                 * For the time being, we do not implement extra process
     3962                 * protection on pre-Vista-SP1 systems as they are lacking
     3963                 * necessary KPIs.  XP is end of life, we do not wish to
     3964                 * spend more time on it, so we don't put up a fuss there.
     3965                 * Vista users without SP1 can install SP1 (or later), darn it,
     3966                 * so refuse to load.
     3967                 */
     3968                /** @todo Hack up an XP solution - will require hooking kernel APIs or doing bad
     3969                 *        stuff to a couple of object types. */
     3970# ifndef VBOX_WITH_VISTA_NO_SP
     3971                if (g_uNtVerCombined >= SUP_NT_VER_VISTA)
     3972# else
     3973                if (g_uNtVerCombined >= SUP_MAKE_NT_VER_COMBINED(6, 0, 6001, 0, 0))
     3974# endif
     3975                {
     3976                    DbgPrint("vboxdrv: ObRegisterCallbacks was not found. Please make sure you got the latest updates and service packs installed\n");
     3977                    rcNt = STATUS_SXS_VERSION_CONFLICT;
     3978                }
     3979                else
     3980                {
     3981                    Log(("vboxdrv: ObRegisterCallbacks was not found; ignored pre-Vista\n"));
     3982                    return rcNt = STATUS_SUCCESS;
     3983                }
     3984                g_pvObCallbacksCookie = NULL;
     3985            }
     3986
     3987            /*
     3988             * Drop process create/term notifications.
     3989             */
     3990            if (g_pfnPsSetCreateProcessNotifyRoutineEx)
     3991                g_pfnPsSetCreateProcessNotifyRoutineEx(supdrvNtProtectCallback_ProcessCreateNotifyEx, TRUE /*fRemove*/);
     3992            else
     3993                PsSetCreateProcessNotifyRoutine(supdrvNtProtectCallback_ProcessCreateNotify, TRUE /*fRemove*/);
     3994        }
     3995        else
     3996            LogRel(("vboxdrv: PsSetCreateProcessNotifyRoutine%s failed with rcNt=%#x\n",
     3997                    g_pfnPsSetCreateProcessNotifyRoutineEx ? "Ex" : "", rcNt));
     3998        supHardenedWinTermImageVerifier();
     3999    }
     4000    else
     4001        rcNt = VBoxDrvNtErr2NtStatus(rc);
     4002
     4003    RTSpinlockDestroy(g_hNtProtectLock);
     4004    g_NtProtectTree = NIL_RTSPINLOCK;
     4005    return rcNt;
     4006}
     4007
     4008#endif /* VBOX_WITH_HARDENING */
     4009
  • trunk/src/VBox/HostDrivers/Support/win/SUPDrvA-win.asm

    r44528 r51770  
    55
    66;
    7 ; Copyright (C) 2006-2010 Oracle Corporation
     7; Copyright (C) 2006-2014 Oracle Corporation
    88;
    99; This file is part of VirtualBox Open Source Edition (OSE), as
     
    4545%endif
    4646
     47
     48%ifdef RT_ARCH_X86
     49;
     50; Faking up ZwQueryVirtualMemory on XP and W2K3 where it's not exported.
     51; Using ZwQueryVolumeInformationFile as a helper.
     52;
     53extern  IMPNAME(ZwQueryVolumeInformationFile@20)
     54
     55BEGINPROC supdrvNtQueryVirtualMemory_Xxx
     56 %macro NtQueryVirtualMemorySyscall 1
     57 GLOBALNAME supdrvNtQueryVirtualMemory_ %+ %1
     58        mov     eax, %1
     59        jmp     supdrvNtQueryVirtualMemory_Jump
     60 %endm
     61    NtQueryVirtualMemorySyscall 0xAF
     62    NtQueryVirtualMemorySyscall 0xB0
     63    NtQueryVirtualMemorySyscall 0xB1
     64    NtQueryVirtualMemorySyscall 0xB2
     65    NtQueryVirtualMemorySyscall 0xB3
     66    NtQueryVirtualMemorySyscall 0xB4
     67    NtQueryVirtualMemorySyscall 0xB5
     68    NtQueryVirtualMemorySyscall 0xB6
     69    NtQueryVirtualMemorySyscall 0xB7
     70    NtQueryVirtualMemorySyscall 0xB8
     71    NtQueryVirtualMemorySyscall 0xB9
     72    NtQueryVirtualMemorySyscall 0xBA
     73    NtQueryVirtualMemorySyscall 0xBB
     74    NtQueryVirtualMemorySyscall 0xBC
     75    NtQueryVirtualMemorySyscall 0xBD
     76    NtQueryVirtualMemorySyscall 0xBE
     77
     78supdrvNtQueryVirtualMemory_Jump:
     79        mov     edx, IMP2(ZwQueryVolumeInformationFile@20)
     80        lea     edx, [edx + 5]
     81        jmp     edx
     82ENDPROC   supdrvNtQueryVirtualMemory_Xxx
     83
     84%endif
     85
     86%ifdef RT_ARCH_AMD64
     87;
     88; Faking up ZwQueryVirtualMemory on XP64 and W2K3-64 where it's not exported.
     89; The C code locates and verifies the essentials in ZwRequestWaitReplyPort.
     90;
     91extern NAME(g_pfnKiServiceLinkage)
     92extern NAME(g_pfnKiServiceInternal)
     93BEGINPROC supdrvNtQueryVirtualMemory_Xxx
     94 %macro NtQueryVirtualMemorySyscall 1
     95 GLOBALNAME supdrvNtQueryVirtualMemory_ %+ %1
     96        mov     eax, %1
     97        jmp     supdrvNtQueryVirtualMemory_Jump
     98 %endm
     99
     100    NtQueryVirtualMemorySyscall 0x1F
     101    NtQueryVirtualMemorySyscall 0x20
     102    NtQueryVirtualMemorySyscall 0x21
     103    NtQueryVirtualMemorySyscall 0x22
     104    NtQueryVirtualMemorySyscall 0x23
     105
     106supdrvNtQueryVirtualMemory_Jump:
     107        cli
     108        mov     r10, rsp                ; save call frame pointer.
     109        mov     r11, [NAME(g_pfnKiServiceLinkage) wrt rip]
     110        push    0
     111        push    0
     112        push    r10                     ; call frame pointer (incoming rsp).
     113        pushfq
     114        push    10h
     115        push    r11                     ; r11 = KiServiceLinkage (ret w/ unwind info)
     116        jmp     qword [NAME(g_pfnKiServiceInternal) wrt rip]
     117ENDPROC   supdrvNtQueryVirtualMemory_Xxx
     118%endif
     119
  • trunk/src/VBox/HostDrivers/Support/win/SUPLib-win.cpp

    r49213 r51770  
    3131#ifdef IN_SUP_HARDENED_R3
    3232# undef DEBUG /* Warning: disables RT_STRICT */
     33# undef LOG_DISABLED
    3334# define LOG_DISABLED
    3435  /** @todo RTLOGREL_DISABLED */
     
    3940
    4041#define USE_NT_DEVICE_IO_CONTROL_FILE
    41 #ifdef USE_NT_DEVICE_IO_CONTROL_FILE
    42 # include <iprt/nt/nt-and-windows.h>
    43 #else
    44 # include <Windows.h>
    45 #endif
     42#include <iprt/nt/nt-and-windows.h>
    4643
    4744#include <VBox/sup.h>
     
    5552#include "../SUPLibInternal.h"
    5653#include "../SUPDrvIOC.h"
     54#ifdef VBOX_WITH_HARDENING
     55# include "win/SUPHardenedVerify-win.h"
     56#endif
    5757
    5858
     
    7575*   Internal Functions                                                         *
    7676*******************************************************************************/
     77#ifndef IN_SUP_HARDENED_R3
    7778static int suplibOsCreateService(void);
    7879//unused: static int suplibOsUpdateService(void);
     
    8081static int suplibOsStartService(void);
    8182static int suplibOsStopService(void);
     83#endif
    8284#ifdef USE_NT_DEVICE_IO_CONTROL_FILE
    8385static int suplibConvertNtStatus(NTSTATUS rcNt);
     
    8789
    8890
    89 
    90 
    9191int suplibOsInit(PSUPLIBDATA pThis, bool fPreInited, bool fUnrestricted)
    9292{
    9393    /*
    94      * Nothing to do if pre-inited.
     94     * Almost nothing to do if pre-inited.
    9595     */
    9696    if (fPreInited)
     97    {
     98#if defined(VBOX_WITH_HARDENING) && !defined(IN_SUP_HARDENED_R3)
     99# ifdef IN_SUP_R3_STATIC
     100        return VERR_NOT_SUPPORTED;
     101# else
     102        supR3HardenedWinInitVersion();
     103        return supHardenedWinInitImageVerifier(NULL);
     104# endif
     105#else
    97106        return VINF_SUCCESS;
     107#endif
     108    }
    98109
    99110    /*
    100111     * Try open the device.
    101112     */
    102     HANDLE hDevice = CreateFile(fUnrestricted ? DEVICE_NAME_SYS : DEVICE_NAME_USR,
    103                                 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
    104                                 NULL,
    105                                 OPEN_EXISTING,
    106                                 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
    107                                 NULL);
    108     if (hDevice == INVALID_HANDLE_VALUE)
    109     {
    110113#ifndef IN_SUP_HARDENED_R3
    111         /*
    112          * Try start the service and retry opening it.
    113          */
    114         suplibOsStartService();
    115 
    116         hDevice = CreateFile(fUnrestricted ? DEVICE_NAME_SYS : DEVICE_NAME_USR,
    117                              GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
    118                              NULL,
    119                              OPEN_EXISTING,
    120                              FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
    121                              NULL);
    122         if (hDevice == INVALID_HANDLE_VALUE)
    123 #endif /* !IN_SUP_HARDENED_R3 */
    124         {
    125             int rc = GetLastError();
    126             switch (rc)
     114    uint32_t cTry = 0;
     115#endif
     116    HANDLE hDevice;
     117    for (;;)
     118    {
     119        IO_STATUS_BLOCK     Ios   = RTNT_IO_STATUS_BLOCK_INITIALIZER;
     120
     121        static const WCHAR  s_wszName[] = L"\\Device\\VBoxDrvU";
     122        UNICODE_STRING      NtName;
     123        NtName.Buffer        = (PWSTR)s_wszName;
     124        NtName.Length        = sizeof(s_wszName) - sizeof(WCHAR) * (fUnrestricted ? 2 : 1);
     125        NtName.MaximumLength = NtName.Length;
     126
     127        OBJECT_ATTRIBUTES   ObjAttr;
     128        InitializeObjectAttributes(&ObjAttr, &NtName, OBJ_CASE_INSENSITIVE, NULL /*hRootDir*/, NULL /*pSecDesc*/);
     129
     130        hDevice = RTNT_INVALID_HANDLE_VALUE;
     131
     132        NTSTATUS rcNt = NtCreateFile(&hDevice,
     133                                     GENERIC_READ | GENERIC_WRITE,
     134                                     &ObjAttr,
     135                                     &Ios,
     136                                     NULL /* Allocation Size*/,
     137                                     FILE_ATTRIBUTE_NORMAL,
     138                                     FILE_SHARE_READ | FILE_SHARE_WRITE,
     139                                     FILE_OPEN,
     140                                     FILE_NON_DIRECTORY_FILE,
     141                                     NULL /*EaBuffer*/,
     142                                     0 /*EaLength*/);
     143        if (NT_SUCCESS(rcNt))
     144            rcNt = Ios.Status;
     145        if (!NT_SUCCESS(rcNt))
     146        {
     147#ifndef IN_SUP_HARDENED_R3
     148            /*
     149             * Failed to open, try starting the service and reopen the device
     150             * exactly once.
     151             */
     152            if (cTry == 0 && !NT_SUCCESS(rcNt))
     153            {
     154                cTry++;
     155                suplibOsStartService();
     156                continue;
     157            }
     158#endif
     159            switch (rcNt)
    127160            {
    128161                /** @todo someone must test what is actually returned. */
    129                 case ERROR_DEV_NOT_EXIST:
    130                 case ERROR_DEVICE_NOT_CONNECTED:
    131                 case ERROR_BAD_DEVICE:
    132                 case ERROR_DEVICE_REMOVED:
    133                 case ERROR_DEVICE_NOT_AVAILABLE:
     162                case STATUS_DEVICE_DOES_NOT_EXIST:
     163                case STATUS_DEVICE_NOT_CONNECTED:
     164                //case ERROR_BAD_DEVICE:
     165                case STATUS_DEVICE_REMOVED:
     166                //case ERROR_DEVICE_NOT_AVAILABLE:
    134167                    return VERR_VM_DRIVER_LOAD_ERROR;
    135                 case ERROR_PATH_NOT_FOUND:
    136                 case ERROR_FILE_NOT_FOUND:
     168                case STATUS_OBJECT_PATH_NOT_FOUND:
     169                case STATUS_NO_SUCH_DEVICE:
     170                case STATUS_NO_SUCH_FILE:
     171                case STATUS_OBJECT_NAME_NOT_FOUND:
    137172                    return VERR_VM_DRIVER_NOT_INSTALLED;
    138                 case ERROR_ACCESS_DENIED:
    139                 case ERROR_SHARING_VIOLATION:
     173                case STATUS_ACCESS_DENIED:
     174                case STATUS_SHARING_VIOLATION:
    140175                    return VERR_VM_DRIVER_NOT_ACCESSIBLE;
     176                case STATUS_UNSUCCESSFUL:
     177                    return VERR_SUPLIB_NT_PROCESS_UNTRUSTED_0;
     178                case STATUS_TRUST_FAILURE:
     179                    return VERR_SUPLIB_NT_PROCESS_UNTRUSTED_1;
     180                case STATUS_TOO_LATE:
     181                    return VERR_SUPDRV_HARDENING_EVIL_HANDLE;
    141182                default:
     183
     184                    return rcNt;
    142185                    return VERR_VM_DRIVER_OPEN_ERROR;
    143186            }
    144 
    145             return -1 /** @todo define proper error codes for suplibOsInit failure. */;
    146         }
     187        }
     188        break;
    147189    }
    148190
     
    154196    return VINF_SUCCESS;
    155197}
    156 
    157198
    158199#ifndef IN_SUP_HARDENED_R3
     
    440481            fRc = StartService(hService, 0, NULL);
    441482            DWORD LastError = GetLastError(); NOREF(LastError);
     483#ifndef DEBUG_bird
    442484            AssertMsg(fRc, ("StartService failed with LastError=%Rwa\n", LastError));
     485#endif
    443486        }
    444487
     
    652695    }
    653696
     697    /* See VBoxDrvNtErr2NtStatus. */
     698    if (((uint32_t)rcNt & 0xffff0000) == UINT32_C(0xe9860000)) /** @todo defines for these? */
     699        return (int)((uint32_t)rcNt | UINT32_C(0xffff0000));
     700
    654701    /* Fall back on IPRT for the rest. */
    655702    return RTErrConvertFromNtStatus(rcNt);
  • trunk/src/VBox/Installer/win/VBoxMergeApp.wxi

    r51318 r51770  
    186186              Source="$(env.PATH_OUT)\bin\VBoxREM64.dll" />
    187187<?endif ?>
     188        <File Id="file_VBoxSupLib.dll" Name="VBoxSupLib.dll"
     189              Source="$(env.PATH_OUT)\bin\VBoxSupLib.dll" />
    188190        <File Id="file_VBoxVMM.dll" Name="VBoxVMM.dll"
    189191              Source="$(env.PATH_OUT)\bin\VBoxVMM.dll" />
  • trunk/src/VBox/Main/src-server/MachineImpl.cpp

    r51643 r51770  
    31653165            LogFlowThisFunc(("mSession.mPID=%d(0x%x)\n", mData->mSession.mPID, mData->mSession.mPID));
    31663166            LogFlowThisFunc(("session.pid=%d(0x%x)\n", pid, pid));
     3167
     3168#if defined(VBOX_WITH_HARDENING) && defined(RT_OS_WINDOWS)
     3169            /* Hardened windows builds have spawns two processes when a VM is
     3170               launched, the 2nd one is the one that will end up here.  */
     3171            RTPROCESS ppid;
     3172            int rc = RTProcQueryParent(pid, &ppid);
     3173            if (   (RT_SUCCESS(rc) && mData->mSession.mPID == ppid)
     3174                || rc == VERR_ACCESS_DENIED)
     3175            {
     3176                LogFlowThisFunc(("mSession.mPID => %d(%#x) - windows hardening stub\n", mData->mSession.mPID, pid));
     3177                mData->mSession.mPID = pid;
     3178            }
     3179#endif
    31673180
    31683181            if (mData->mSession.mPID != pid)
  • trunk/src/VBox/NetworkServices/DHCP/Makefile.kmk

    r49824 r51770  
    3636VBoxNetDHCPHardened_SOURCES = VBoxNetDHCPHardened.cpp
    3737VBoxNetDHCPHardened_NAME = VBoxNetDHCP
     38VBoxNetDHCPHardened_LDFLAGS.win = /SUBSYSTEM:windows
    3839
    3940
  • trunk/src/VBox/NetworkServices/NAT/Makefile.kmk

    r51156 r51770  
    3636 VBoxNetLwipNATHardened_TEMPLATE=VBOXR3HARDENEDEXE
    3737 VBoxNetLwipNATHardened_NAME = VBoxNetNAT
     38 VBoxNetLwipNATHardened_LDFLAGS.win = /SUBSYSTEM:windows
    3839endif
    3940
  • trunk/src/VBox/RDP/client/Makefile.in

    r38517 r51770  
    2929SCARDOBJ    = @SCARDOBJ@
    3030
    31 RDPOBJ   = tcp.o iso.o mcs.o secure.o licence.o rdp.o orders.o bitmap.o cache.o rdp5.o channels.o rdpdr.o serial.o printer.o disk.o parallel.o printercache.o mppc.o pstcache.o lspci.o seamless.o ssl.o Runtime/common/alloc/alloc.o Runtime/common/err/errmsg.o Runtime/common/err/errmsgxpcom.o Runtime/common/err/RTErrConvertFromErrno.o Runtime/common/err/RTErrConvertToErrno.o Runtime/common/path/RTPathAppend.o Runtime/common/path/RTPathAppendEx.o Runtime/common/path/RTPathCountComponents.o Runtime/common/path/RTPathFilename.o Runtime/common/path/rtPathRootSpecLen.o Runtime/common/path/RTPathStripFilename.o Runtime/common/path/RTPathStripTrailingSlash.o Runtime/common/path/rtPathVolumeSpecLen.o Runtime/common/string/RTStrCmp.o Runtime/common/string/RTStrNCmp.o Runtime/common/string/RTStrCopy.o Runtime/common/string/RTStrNLen.o Runtime/common/string/straprintf.o Runtime/common/string/stringalloc.o Runtime/common/string/strformat.o Runtime/common/string/strformatrt.o Runtime/common/string/strformattype.o Runtime/common/string/strprintf.o Runtime/common/string/strstrip.o Runtime/common/string/strtonum.o Runtime/common/string/unidata.o Runtime/common/string/utf-16.o Runtime/common/string/utf-8.o Runtime/common/string/utf-8-case.o Runtime/common/time/timesysalias.o Runtime/generic/pathhost-generic.o Runtime/r3/alloc.o Runtime/r3/dir.o Runtime/r3/fileio.o Runtime/r3/fs.o Runtime/r3/linux/sysfs.o Runtime/r3/linux/time-linux.o Runtime/r3/posix/dir-posix.o Runtime/r3/posix/env-posix.o Runtime/r3/posix/fileio-posix.o Runtime/r3/posix/fs2-posix.o Runtime/r3/posix/fs3-posix.o Runtime/r3/posix/path-posix.o Runtime/r3/posix/path2-posix.o Runtime/r3/posix/utf8-posix.o Runtime/r3/stream.o vrdp/rdpusb.o vrdp/USBGetDevices.o vrdp/USBLib.o vrdp/linux/USBProxyDevice-linux.o
     31RDPOBJ   = tcp.o iso.o mcs.o secure.o licence.o rdp.o orders.o bitmap.o cache.o rdp5.o channels.o rdpdr.o serial.o printer.o disk.o parallel.o printercache.o mppc.o pstcache.o lspci.o seamless.o ssl.o Runtime/common/alloc/alloc.o Runtime/common/err/errmsg.o Runtime/common/err/errmsgxpcom.o Runtime/common/err/RTErrConvertFromErrno.o Runtime/common/err/RTErrConvertToErrno.o Runtime/common/misc/sg.o Runtime/common/path/RTPathAppend.o Runtime/common/path/RTPathAppendEx.o Runtime/common/path/RTPathCountComponents.o Runtime/common/path/RTPathFilename.o Runtime/common/path/rtPathRootSpecLen.o Runtime/common/path/RTPathStripFilename.o Runtime/common/path/RTPathStripTrailingSlash.o Runtime/common/path/rtPathVolumeSpecLen.o Runtime/common/string/RTStrCmp.o Runtime/common/string/RTStrNCmp.o Runtime/common/string/RTStrCopy.o Runtime/common/string/RTStrNLen.o Runtime/common/string/straprintf.o Runtime/common/string/stringalloc.o Runtime/common/string/strformat.o Runtime/common/string/strformatrt.o Runtime/common/string/strformattype.o Runtime/common/string/strprintf.o Runtime/common/string/strstrip.o Runtime/common/string/strtonum.o Runtime/common/string/unidata-flags.o Runtime/common/string/unidata-upper.o Runtime/common/string/unidata-lower.o Runtime/common/string/utf-16.o Runtime/common/string/utf-8.o Runtime/common/string/utf-8-case.o Runtime/common/time/timesysalias.o Runtime/generic/pathhost-generic.o Runtime/r3/alloc.o Runtime/r3/dir.o Runtime/r3/fileio.o Runtime/r3/fs.o Runtime/r3/linux/sysfs.o Runtime/r3/linux/time-linux.o Runtime/r3/posix/dir-posix.o Runtime/r3/posix/env-posix.o Runtime/r3/posix/fileio-posix.o Runtime/r3/posix/fs2-posix.o Runtime/r3/posix/fs3-posix.o Runtime/r3/posix/path-posix.o Runtime/r3/posix/path2-posix.o Runtime/r3/posix/pipe-posix.o Runtime/r3/posix/thread2-posix.o Runtime/r3/posix/utf8-posix.o Runtime/r3/stream.o vrdp/rdpusb.o vrdp/USBGetDevices.o vrdp/USBLib.o vrdp/linux/USBProxyDevice-linux.o
    3232X11OBJ   = rdesktop.o xwin.o xkeymap.o ewmhints.o xclip.o cliprdr.o
    3333VNCOBJ   = vnc/rdp2vnc.o vnc/vnc.o vnc/xkeymap.o vnc/x11stubs.o
  • trunk/src/VBox/RDP/client/Makefile.kmk

    r41477 r51770  
    271271        $(PATH_ROOT)/include/iprt/cdefs.h=>include/iprt/cdefs.h \
    272272        $(PATH_ROOT)/include/iprt/cpp/autores.h=>include/iprt/cpp/autores.h \
     273        $(PATH_ROOT)/include/iprt/critsect.h=>include/iprt/critsect.h \
    273274        $(PATH_ROOT)/include/iprt/ctype.h=>include/iprt/ctype.h \
    274275        $(PATH_ROOT)/include/iprt/dir.h=>include/iprt/dir.h \
    275276        $(PATH_ROOT)/include/iprt/env.h=>include/iprt/env.h \
    276277        $(PATH_ROOT)/include/iprt/err.h=>include/iprt/err.h \
     278        $(PATH_ROOT)/include/iprt/errno.h=>include/iprt/errno.h \
    277279        $(PATH_ROOT)/include/iprt/file.h=>include/iprt/file.h \
    278280        $(PATH_ROOT)/include/iprt/fs.h=>include/iprt/fs.h \
     
    280282        $(PATH_ROOT)/include/iprt/list.h=>include/iprt/list.h \
    281283        $(PATH_ROOT)/include/iprt/log.h=>include/iprt/log.h \
     284        $(PATH_ROOT)/include/iprt/lockvalidator.h=>include/iprt/lockvalidator.h \
    282285        $(PATH_ROOT)/include/iprt/mem.h=>include/iprt/mem.h \
    283286        $(PATH_ROOT)/include/iprt/net.h=>include/iprt/net.h \
    284287        $(PATH_ROOT)/include/iprt/param.h=>include/iprt/param.h \
    285288        $(PATH_ROOT)/include/iprt/path.h=>include/iprt/path.h \
     289        $(PATH_ROOT)/include/iprt/pipe.h=>include/iprt/pipe.h \
     290        $(PATH_ROOT)/include/iprt/poll.h=>include/iprt/poll.h \
    286291        $(PATH_ROOT)/include/iprt/process.h=>include/iprt/process.h \
     292        $(PATH_ROOT)/include/iprt/queueatomic.h=>include/iprt/queueatomic.h \
     293        $(PATH_ROOT)/include/iprt/sg.h=>include/iprt/sg.h \
    287294        $(PATH_ROOT)/include/iprt/stdarg.h=>include/iprt/stdarg.h \
    288295        $(PATH_ROOT)/include/iprt/stdint.h=>include/iprt/stdint.h \
     
    315322        $(PATH_ROOT)/src/VBox/Runtime/common/err/RTErrConvertFromErrno.cpp=>Runtime/common/err/RTErrConvertFromErrno.cpp \
    316323        $(PATH_ROOT)/src/VBox/Runtime/common/err/RTErrConvertToErrno.cpp=>Runtime/common/err/RTErrConvertToErrno.cpp \
     324        $(PATH_ROOT)/src/VBox/Runtime/common/misc/sg.cpp=>Runtime/common/misc/sg.cpp \
    317325        $(PATH_ROOT)/src/VBox/Runtime/common/path/RTPathAppend.cpp=>Runtime/common/path/RTPathAppend.cpp \
    318326        $(PATH_ROOT)/src/VBox/Runtime/common/path/RTPathAppendEx.cpp=>Runtime/common/path/RTPathAppendEx.cpp \
     
    335343        $(PATH_ROOT)/src/VBox/Runtime/common/string/strstrip.cpp=>Runtime/common/string/strstrip.cpp \
    336344        $(PATH_ROOT)/src/VBox/Runtime/common/string/strtonum.cpp=>Runtime/common/string/strtonum.cpp \
    337         $(PATH_ROOT)/src/VBox/Runtime/common/string/unidata.cpp=>Runtime/common/string/unidata.cpp \
     345        $(PATH_ROOT)/src/VBox/Runtime/common/string/unidata-flags.cpp=>Runtime/common/string/unidata-flags.cpp \
     346        $(PATH_ROOT)/src/VBox/Runtime/common/string/unidata-upper.cpp=>Runtime/common/string/unidata-upper.cpp \
     347        $(PATH_ROOT)/src/VBox/Runtime/common/string/unidata-lower.cpp=>Runtime/common/string/unidata-lower.cpp \
    338348        $(PATH_ROOT)/src/VBox/Runtime/common/string/utf-16.cpp=>Runtime/common/string/utf-16.cpp \
    339349        $(PATH_ROOT)/src/VBox/Runtime/common/string/utf-8.cpp=>Runtime/common/string/utf-8.cpp \
     
    346356        $(PATH_ROOT)/src/VBox/Runtime/include/internal/fs.h=>include/internal/fs.h \
    347357        $(PATH_ROOT)/src/VBox/Runtime/include/internal/iprt.h=>include/internal/iprt.h \
     358        $(PATH_ROOT)/src/VBox/Runtime/include/internal/lockvalidator.h=>include/internal/lockvalidator.h \
    348359        $(PATH_ROOT)/src/VBox/Runtime/include/internal/magics.h=>include/internal/magics.h \
    349360        $(PATH_ROOT)/src/VBox/Runtime/include/internal/mem.h=>include/internal/mem.h \
    350361        $(PATH_ROOT)/src/VBox/Runtime/include/internal/path.h=>include/internal/path.h \
     362        $(PATH_ROOT)/src/VBox/Runtime/include/internal/pipe.h=>include/internal/pipe.h \
    351363        $(PATH_ROOT)/src/VBox/Runtime/include/internal/process.h=>include/internal/process.h \
    352364        $(PATH_ROOT)/src/VBox/Runtime/include/internal/string.h=>include/internal/string.h \
     365        $(PATH_ROOT)/src/VBox/Runtime/include/internal/thread.h=>include/internal/thread.h \
    353366        $(PATH_ROOT)/src/VBox/Runtime/include/internal/time.h=>include/internal/time.h \
    354367        $(PATH_ROOT)/src/VBox/Runtime/r3/alloc.cpp=>Runtime/r3/alloc.cpp \
     
    366379        $(PATH_ROOT)/src/VBox/Runtime/r3/posix/path-posix.cpp=>Runtime/r3/posix/path-posix.cpp \
    367380        $(PATH_ROOT)/src/VBox/Runtime/r3/posix/path2-posix.cpp=>Runtime/r3/posix/path2-posix.cpp \
     381        $(PATH_ROOT)/src/VBox/Runtime/r3/posix/pipe-posix.cpp=>Runtime/r3/posix/pipe-posix.cpp \
     382        $(PATH_ROOT)/src/VBox/Runtime/r3/posix/thread2-posix.cpp=>Runtime/r3/posix/thread2-posix.cpp \
    368383        $(PATH_ROOT)/src/VBox/Runtime/r3/posix/utf8-posix.cpp=>Runtime/r3/posix/utf8-posix.cpp \
    369384        $(PATH_ROOT)/src/VBox/Runtime/r3/stream.cpp=>Runtime/r3/stream.cpp
  • trunk/src/VBox/Runtime/Makefile.kmk

    r51714 r51770  
    146146
    147147#
    148 # Unicode Specification reader used to regenerate unidata.cpp.
     148# Unicode Specification reader used to regenerate unidata-*.cpp.
    149149#
    150150uniread_TEMPLATE = VBoxBldProg
     
    226226RuntimeR3_SDKS          = VBOX_OPENSSL VBOX_LIBXML2
    227227RuntimeR3_SDKS.win      = $(VBOX_WINPSDK) $(VBOX_WINDDK)
    228 RuntimeR3_DEFS          = IN_RT_R3 IN_SUP_R3 LDR_WITH_NATIVE LDR_WITH_ELF32 LDR_WITH_PE RT_WITH_VBOX RT_NO_GIP
     228RuntimeR3_DEFS          = \
     229        IN_RT_R3 \
     230        IN_SUP_R3 \
     231        LDR_WITH_NATIVE \
     232        LDR_WITH_ELF32 \
     233        LDR_WITH_PE \
     234        RT_WITH_VBOX \
     235        RT_NO_GIP \
     236        RT_WITHOUT_NOCRT_WRAPPERS \
     237       IPRT_WITH_OPENSSL
    229238#RuntimeR3_DEFS         += RTMEM_WRAP_TO_EF_APIS
    230239ifdef IPRT_WITH_KSTUFF
     
    262271        common/alloc/memcache.cpp \
    263272        common/alloc/memtracker.cpp \
     273        common/asn1/asn1-basics.cpp \
     274        common/asn1/asn1-cursor.cpp \
     275        common/asn1/asn1-default-allocator.cpp \
     276        common/asn1/asn1-dump.cpp \
     277        common/asn1/asn1-encode.cpp \
     278        common/asn1/asn1-ut-bitstring.cpp \
     279        common/asn1/asn1-ut-bitstring-decode.cpp \
     280        common/asn1/asn1-ut-boolean.cpp \
     281        common/asn1/asn1-ut-boolean-decode.cpp \
     282        common/asn1/asn1-ut-core.cpp \
     283        common/asn1/asn1-ut-core-decode.cpp \
     284        common/asn1/asn1-ut-dyntype.cpp \
     285        common/asn1/asn1-ut-dyntype-decode.cpp \
     286        common/asn1/asn1-ut-integer.cpp \
     287        common/asn1/asn1-ut-integer-decode.cpp \
     288        common/asn1/asn1-ut-null.cpp \
     289        common/asn1/asn1-ut-null-decode.cpp \
     290        common/asn1/asn1-ut-objid.cpp \
     291        common/asn1/asn1-ut-objid-decode.cpp \
     292        common/asn1/asn1-ut-octetstring.cpp \
     293        common/asn1/asn1-ut-octetstring-decode.cpp \
     294        common/asn1/asn1-ut-string.cpp \
     295        common/asn1/asn1-ut-string-decode.cpp \
     296        common/asn1/asn1-ut-time.cpp \
     297        common/asn1/asn1-ut-time-decode.cpp \
    264298        common/checksum/adler32.cpp \
    265299        common/checksum/crc32.cpp \
    266300        common/checksum/crc32c.cpp \
    267301        common/checksum/crc64.cpp \
     302        common/checksum/md2.cpp \
     303        common/checksum/md2str.cpp \
    268304        common/checksum/md5.cpp \
    269305        common/checksum/md5str.cpp \
     
    283319        common/checksum/sha512str.cpp \
    284320        common/checksum/x509.cpp \
     321        common/crypto/digest-core.cpp \
     322        common/crypto/digest-builtin.cpp \
     323        common/crypto/iprt-openssl.cpp \
     324        common/crypto/rsa-asn1-decoder.cpp \
     325        common/crypto/rsa-core.cpp \
     326        common/crypto/rsa-init.cpp \
     327        common/crypto/rsa-sanity.cpp \
     328        common/crypto/pemfile.cpp \
     329        common/crypto/pkcs7-asn1-decoder.cpp \
     330        common/crypto/pkcs7-core.cpp \
     331        common/crypto/pkcs7-init.cpp \
     332        common/crypto/pkcs7-sanity.cpp \
     333        common/crypto/pkcs7-verify.cpp \
     334        common/crypto/pkix-signature-builtin.cpp \
     335        common/crypto/pkix-signature-core.cpp \
     336        common/crypto/pkix-signature-rsa.cpp \
     337        common/crypto/pkix-util.cpp \
     338        common/crypto/pkix-verify.cpp \
     339        common/crypto/spc-asn1-decoder.cpp \
     340        common/crypto/spc-core.cpp \
     341        common/crypto/spc-init.cpp \
     342        common/crypto/spc-sanity.cpp \
     343        common/crypto/x509-asn1-decoder.cpp \
     344        common/crypto/x509-certpaths.cpp \
     345        common/crypto/x509-core.cpp \
     346        common/crypto/x509-file.cpp \
     347        common/crypto/x509-init.cpp \
     348        common/crypto/x509-sanity.cpp \
     349        common/crypto/x509-verify.cpp \
     350        common/crypto/taf-asn1-decoder.cpp \
     351        common/crypto/taf-core.cpp \
     352        common/crypto/taf-init.cpp \
     353        common/crypto/taf-sanity.cpp \
     354        common/crypto/store.cpp \
     355        common/crypto/store-inmem.cpp \
     356        common/crypto/RTCrStoreCertAddFromFile.cpp \
    285357        common/dbg/dbg.cpp \
    286358        common/dbg/dbgas.cpp \
     
    300372        common/dvm/dvmvfs.cpp \
    301373        common/err/errinfo.cpp \
     374        common/err/errinfo-alloc.cpp \
    302375        common/err/errmsg.cpp \
    303376        common/err/RTErrConvertFromErrno.cpp \
     
    320393        common/log/tracebuf.cpp \
    321394        common/log/tracedefault.cpp \
     395        common/math/bignum.cpp \
    322396        common/misc/RTAssertMsg1Weak.cpp \
    323397        common/misc/RTAssertMsg2.cpp \
     
    409483        common/string/RTStrPrintHexBytes.cpp \
    410484        common/string/RTStrStr.cpp \
     485        common/string/RTUtf16Copy.cpp \
     486        common/string/RTUtf16CopyAscii.cpp \
     487        common/string/RTUtf16Cat.cpp \
     488        common/string/RTUtf16CatAscii.cpp \
     489        common/string/RTUtf16CmpAscii.cpp \
     490        common/string/RTUtf16ICmpAscii.cpp \
     491        common/string/RTUtf16End.cpp \
     492        common/string/RTUtf16NLen.cpp \
     493        common/string/RTUtf16NLenEx.cpp \
     494        common/string/RTUtf16PrintHexBytes.cpp \
    411495        common/string/base64.cpp \
    412496        common/string/simplepattern.cpp \
     
    425509        common/string/strversion.cpp \
    426510        common/string/uni.cpp \
    427         common/string/unidata.cpp \
     511        common/string/unidata-flags.cpp \
     512        common/string/unidata-lower.cpp \
     513        common/string/unidata-upper.cpp \
    428514        common/string/utf-16.cpp \
     515        common/string/utf-16-case.cpp \
     516        common/string/utf-16-latin-1.cpp \
    429517        common/string/utf-8.cpp \
    430518        common/string/utf-8-case.cpp \
     519        common/string/utf-8-case2.cpp \
    431520        common/string/ministring.cpp \
    432521        common/table/avlgcptr.cpp \
     
    490579        generic/RTTimerLRCreate-generic.cpp \
    491580        generic/mempool-generic.cpp \
     581        generic/memsafer-generic.cpp \
    492582        generic/semfastmutex-generic.cpp \
    493583        generic/semxroads-generic.cpp \
     
    610700        r3/nt/fs-nt.cpp \
    611701        r3/nt/pathint-nt.cpp \
     702        r3/nt/RTProcQueryParent-r3-nt.cpp \
    612703        r3/win/env-win.cpp \
    613704        r3/win/RTHandleGetStandard-win.cpp \
     
    647738        r3/win/RTUuidCreate-win.cpp \
    648739        win/errmsgwin.cpp \
    649         win/RTErrConvertFromWin32.cpp
     740        win/RTErrConvertFromWin32.cpp \
     741        common/string/mempcpy.asm
    650742
    651743RuntimeR3_SOURCES.win.amd64 := $(RuntimeWin64ASM_SOURCES)
     
    10901182#       for build programs.
    10911183#
    1092 RuntimeBldProg_TEMPLATE         := VBoxAdvBldProg
    1093 RuntimeBldProg_EXTENDS          := RuntimeR3
    1094 RuntimeBldProg_BLD_TRG          := $(KBUILD_HOST)
    1095 RuntimeBldProg_BLD_TRG_ARCH     := $(KBUILD_HOST_ARCH)
    1096 RuntimeBldProg_BLD_TRG_CPU      := $(KBUILD_HOST_CPU)
     1184RuntimeBldProg_TEMPLATE        := VBoxAdvBldProg
     1185RuntimeBldProg_EXTENDS         := RuntimeR3
     1186RuntimeBldProg_BLD_TRG         := $(KBUILD_HOST)
     1187RuntimeBldProg_BLD_TRG_ARCH    := $(KBUILD_HOST_ARCH)
     1188RuntimeBldProg_BLD_TRG_CPU     := $(KBUILD_HOST_CPU)
     1189RuntimeBldProg_DEFS            := $(RuntimeR3_DEFS) IPRT_WITHOUT_LDR_VERIFY
    10971190RuntimeBldProg_SOURCES          = $(filter-out \
    10981191        r3/xml.cpp \
     
    11101203## @todo change this to EXTEND the RuntimeR3 target.
    11111204RuntimeGuestR3_SDKS.win                 := $(RuntimeR3_SDKS.win)
    1112 RuntimeGuestR3_DEFS                     := $(filter-out RTCRITSECT_STRICT RT_NO_GIP, $(RuntimeR3_DEFS))
     1205RuntimeGuestR3_DEFS                     := $(filter-out RTCRITSECT_STRICT RT_NO_GIP IPRT_WITH_OPENSSL, $(RuntimeR3_DEFS))
    11131206RuntimeGuestR3_DEFS.$(KBUILD_TARGET)    := $(RuntimeR3_DEFS.$(KBUILD_TARGET))
    11141207RuntimeGuestR3_DEFS.$(KBUILD_HOST)      := $(RuntimeR3_DEFS.$(KBUILD_HOST))
     
    11231216        common/checksum/RTSha256Digest.cpp \
    11241217        common/checksum/sha% \
     1218        common/checksum/md2% \
    11251219        common/checksum/x509.cpp \
    11261220        generic/RTLogWriteUser-generic.cpp \
     
    12381332        common/string/strprintf.cpp \
    12391333        common/string/strtonum.cpp \
    1240         common/string/unidata.cpp \
     1334        common/string/unidata-flags.cpp \
     1335        common/string/unidata-lower.cpp \
     1336        common/string/unidata-upper.cpp \
    12411337        common/string/utf-8.cpp \
    12421338        common/string/utf-8-case.cpp \
     1339        common/string/utf-8-case2.cpp \
    12431340        common/string/utf-16.cpp \
     1341        common/string/utf-16-case.cpp \
     1342        common/string/utf-16-latin-1.cpp \
    12441343        common/table/avlpv.cpp \
    12451344        generic/critsect-generic.cpp \
     
    13121411VBoxRT_SDKS                   += VBOX_OPENSSL
    13131412VBoxRT_SDKS.win                = $(VBOX_WINPSDK) $(VBOX_WINDDK) VBOX_NTDLL
    1314 if1of ($(KBUILD_TARGET)$(VBOX_WITH_HARDENING), darwin win)
     1413if1of ($(KBUILD_TARGET)$(VBOX_WITH_HARDENING), darwin win$(VBOX_WITH_HARDENING))
    13151414VBoxRT_INST                    = $(INST_DLL) $(INST_TESTCASE)
    13161415endif
     
    17221821#
    17231822RuntimeR0Drv_TEMPLATE   = VBoxR0DrvLib
    1724 RuntimeR0Drv_SDKS.win   = ReorderCompilerIncs $(VBOX_WINDDK) $(VBOX_WINPSDK)INCS
     1823RuntimeR0Drv_SDKS.win   = ReorderCompilerIncs $(VBOX_WINDDK) $(VBOX_WINPSDK)INCS VBOX_OPENSSL
    17251824RuntimeR0Drv_DEFS       = IN_RT_R0 RT_WITH_VBOX RT_WITHOUT_NOCRT_WRAPPERS RT_NO_EXPORT_SYMBOL
    1726 RuntimeR0Drv_DEFS.win   = IN_SUP_R0
     1825RuntimeR0Drv_DEFS.win   = IN_SUP_R0 LDR_ONLY_PE
    17271826RuntimeR0Drv_DEFS.linux = MODULE KBUILD_MODNAME=KBUILD_STR\(vboxdrv\) KBUILD_BASENAME=KBUILD_STR\(vboxdrv\) IN_SUP_R0
    17281827
     
    17711870        common/misc/sanity-cpp.cpp \
    17721871        common/misc/term.cpp \
     1872        common/misc/RTMemWipeThoroughly.cpp \
    17731873        common/path/rtPathVolumeSpecLen.cpp \
    17741874        common/path/RTPathAbsDup.cpp \
     
    18101910        common/string/strtonum.cpp \
    18111911        common/string/stringalloc.cpp \
     1912        common/string/unidata-flags.cpp \
     1913        common/string/unidata-lower.cpp \
     1914        common/string/unidata-upper.cpp \
     1915        common/string/utf-8.cpp \
     1916        common/string/utf-8-case.cpp \
     1917        common/string/utf-8-case2.cpp \
    18121918        common/string/utf-16.cpp \
    1813         common/string/utf-8.cpp \
     1919        common/string/utf-16-case.cpp \
     1920        common/string/utf-16-latin-1.cpp \
    18141921        common/table/avlpv.cpp \
    18151922        common/time/time.cpp \
     
    18681975
    18691976RuntimeR0Drv_SOURCES.win = \
     1977        common/ldr/ldr.cpp \
     1978        common/ldr/ldrEx.cpp \
     1979        common/ldr/ldrPE.cpp \
     1980        common/asn1/asn1-basics.cpp \
     1981        common/asn1/asn1-dump.cpp \
     1982        common/asn1/asn1-cursor.cpp \
     1983        common/asn1/asn1-default-allocator.cpp \
     1984        common/asn1/asn1-encode.cpp \
     1985        common/asn1/asn1-ut-bitstring.cpp \
     1986        common/asn1/asn1-ut-bitstring-decode.cpp \
     1987        common/asn1/asn1-ut-boolean.cpp \
     1988        common/asn1/asn1-ut-boolean-decode.cpp \
     1989        common/asn1/asn1-ut-core.cpp \
     1990        common/asn1/asn1-ut-core-decode.cpp \
     1991        common/asn1/asn1-ut-dyntype.cpp \
     1992        common/asn1/asn1-ut-dyntype-decode.cpp \
     1993        common/asn1/asn1-ut-integer.cpp \
     1994        common/asn1/asn1-ut-integer-decode.cpp \
     1995        common/asn1/asn1-ut-null.cpp \
     1996        common/asn1/asn1-ut-null-decode.cpp \
     1997        common/asn1/asn1-ut-objid.cpp \
     1998        common/asn1/asn1-ut-objid-decode.cpp \
     1999        common/asn1/asn1-ut-octetstring.cpp \
     2000        common/asn1/asn1-ut-octetstring-decode.cpp \
     2001        common/asn1/asn1-ut-string.cpp \
     2002        common/asn1/asn1-ut-string-decode.cpp \
     2003        common/asn1/asn1-ut-time.cpp \
     2004        common/asn1/asn1-ut-time-decode.cpp \
     2005        common/crypto/digest-core.cpp \
     2006        common/crypto/digest-builtin.cpp \
     2007        common/crypto/rsa-asn1-decoder.cpp \
     2008        common/crypto/rsa-core.cpp \
     2009        common/crypto/rsa-init.cpp \
     2010        common/crypto/rsa-sanity.cpp \
     2011        common/crypto/pkcs7-asn1-decoder.cpp \
     2012        common/crypto/pkcs7-core.cpp \
     2013        common/crypto/pkcs7-init.cpp \
     2014        common/crypto/pkcs7-sanity.cpp \
     2015        common/crypto/pkcs7-verify.cpp \
     2016        common/crypto/pkix-signature-builtin.cpp \
     2017        common/crypto/pkix-signature-core.cpp \
     2018        common/crypto/pkix-signature-rsa.cpp \
     2019        common/crypto/pkix-util.cpp \
     2020        common/crypto/pkix-verify.cpp \
     2021        common/crypto/spc-asn1-decoder.cpp \
     2022        common/crypto/spc-core.cpp \
     2023        common/crypto/spc-init.cpp \
     2024        common/crypto/spc-sanity.cpp \
     2025        common/crypto/x509-asn1-decoder.cpp \
     2026        common/crypto/x509-certpaths.cpp \
     2027        common/crypto/x509-core.cpp \
     2028        common/crypto/x509-init.cpp \
     2029        common/crypto/x509-sanity.cpp \
     2030        common/crypto/x509-verify.cpp \
     2031        common/crypto/store.cpp \
     2032        common/crypto/store-inmem.cpp \
     2033        common/crypto/taf-asn1-decoder.cpp \
     2034        common/crypto/taf-core.cpp \
     2035        common/crypto/taf-init.cpp \
     2036        common/crypto/taf-sanity.cpp \
     2037        common/checksum/md2.cpp \
     2038        common/checksum/sha1.cpp \
     2039        common/checksum/sha256.cpp \
     2040        common/checksum/sha512.cpp \
     2041        common/checksum/md2str.cpp \
     2042        common/checksum/md5str.cpp \
     2043        common/checksum/sha1str.cpp \
     2044        common/checksum/sha256str.cpp \
     2045        common/checksum/sha512str.cpp \
     2046        common/err/errinfo.cpp \
     2047        common/path/RTPathChangeToUnixSlashes.cpp \
     2048        common/math/bignum.cpp \
     2049        common/string/RTStrPrintHexBytes.cpp \
     2050        common/string/RTUtf16Copy.cpp \
     2051        common/string/RTUtf16CopyAscii.cpp \
     2052        common/string/RTUtf16Cat.cpp \
     2053        common/string/RTUtf16CatAscii.cpp \
     2054        common/string/RTUtf16End.cpp \
     2055        common/string/RTUtf16NLen.cpp \
     2056        common/string/RTUtf16NLenEx.cpp \
     2057        common/string/RTUtf16PrintHexBytes.cpp \
     2058        common/string/strstrip.cpp \
     2059        generic/memsafer-generic.cpp \
     2060       \
    18702061        common/misc/thread.cpp \
    18712062        common/string/memcmp.asm \
     
    19052096        r0drv/nt/time-r0drv-nt.cpp \
    19062097        r0drv/nt/timer-r0drv-nt.cpp \
     2098        r0drv/nt/toxic-chkstk-r0drv-nt.asm \
    19072099        r0drv/nt/RTTimerGetSystemGranularity-r0drv-nt.cpp
    19082100
     
    22662458#           images that does not load on older windows versions.
    22672459#
     2460if1of (win,$(KBUILD_TARGET) $(KBUILD_HOST))
    22682461RuntimeR3NtDll-amd64_TEMPLATE     = VBoxR3Dll
    22692462RuntimeR3NtDll-amd64_BLD_TRG_ARCH = amd64
    22702463RuntimeR3NtDll-amd64_ARFLAGS      = /NODEFAULTLIB /MACHINE:amd64
    22712464RuntimeR3NtDll-amd64_SOURCES      = \
    2272         r3/win/ntdll-mini-implib.c \
    22732465        r3/win/ntdll-mini-implib.def
    22742466
    2275 RuntimeR3NtDll-x86_EXTENDS        = RuntimeR3NtDll-amd64
     2467RuntimeR3NtDll-x86_TEMPLATE       = VBoxR3Dll
    22762468RuntimeR3NtDll-x86_BLD_TRG_ARCH   = x86
    22772469RuntimeR3NtDll-x86_ARFLAGS        = /NODEFAULTLIB /MACHINE:x86
    2278 
     2470RuntimeR3NtDll-x86_SOURCES        = \
     2471        r3/win/ntdll-mini-implib.def \
     2472        $(RuntimeR3NtDll-x86_0_OUTDIR)/ntdll-mini-implib.asm
     2473RuntimeR3NtDll-x86_CLEAN          = \
     2474        $(RuntimeR3NtDll-x86_0_OUTDIR)/ntdll-mini-implib.asm
     2475
     2476$$(RuntimeR3NtDll-x86_0_OUTDIR)/ntdll-mini-implib.asm: $(PATH_SUB_CURRENT)/r3/win/ntdll-mini-implib.def | $$(dir $$@)
     2477        $(call MSG_GENERATE,,$@,$<)
     2478        $(QUIET)$(APPEND) -nt "$@" \
     2479                ';Autogenerated, do not edit' \
     2480                '%include "iprt/asmdefs.mac"' \
     2481               'BEGINCODE' \
     2482               '%macro IMPLIB_EXPORT 1' \
     2483               'global %1:function' \
     2484               '%1: nop' \
     2485               '%endm' \
     2486               ''
     2487        $(QUIET)$(SED) -e '1,/EXPORTS/d' \
     2488                -e 's/^.*;;=[[:space:]]*\([^[:space:]]*\)[[:space:]]*$$/IMPLIB_EXPORT \1/' \
     2489                $< --append $@
     2490endif
    22792491
    22802492#
     
    25052717 else
    25062718# Generate a SED script from mangling.h that checks for known symbols.
    2507         @$(SED) \
     2719        $(QUIET)$(SED) \
    25082720                -e '/# *define.*RT_MANGLER/!d' \
    25092721                -e 's/^.*RT_MANGLER(\([^)][^)]*\)).*$(DOLLAR)/\/^\1$(DOLLAR)\/b ok/' \
    25102722                $(PATH_ROOT)/include/iprt/mangling.h \
    25112723                --output "$@"
    2512         @$(APPEND) -n '$@' \
     2724        $(QUIET)$(APPEND) -n '$@' \
    25132725                ':bad' \
    2514                 's/^\(.*\)$(DOLLAR)/error: Missing # define \1   RT_MANGLER(\1)/' \
     2726                's/^\(.*\)$(DOLLAR)/error: Missing # define \1 /' \
     2727               ':bad-pad' \
     2728               '/^.\{0,70\}$(DOLLAR)/ { s/$(DOLLAR)/ /; bbad-pad; }' \
     2729               's/define \([^ ]*\) \([ ]*\)$(DOLLAR)/define \1 \2RT_MANGLER(\1)/' \
    25152730                'p' \
    2516                 'q 1' \
     2731                $(if-expr !defined(IPRT_IGNORE_TEST_MANGLING),'q 1') \
    25172732                '' \
    25182733                ':ok' \
     
    25212736  if $(intersects $(KBUILD_TARGET), linux) && "$(VBOX_GCC_fvisibility-hidden)"
    25222737        $(call MSG_L1,IPRT: Testing mangling and visiblity for newer gcc...)
    2523         @readelf -Ws $^ \
     2738        $(QUIET)readelf -Ws $^ \
    25242739                | $(SED) \
     2740                -e 's/[[:space:]]\+/ /g' \
    25252741                        -e '/^  *[[:digit:]]\+:/!d' \
    25262742                        -e 's/^ \+[[:digit:]]\+: \+[[:xdigit:]]\+ \+[[:digit:]]\+ \+//' \
     
    25302746                        -e '/LOCAL/d' \
    25312747                        -e 's/^[[:alpha:]]\+ \+//' \
     2748                       -e '/^HIDDEN [[:xdigit:]]\+ RT/bkeep-hidden' \
     2749                       -e '/^HIDDEN [[:xdigit:]]\+ g_[a-z0-9]*RT/bkeep-hidden' \
    25322750                        -e '/^HIDDEN/d' \
     2751                        -e ':keep-hidden' \
    25332752                        -e 's/^[[:alpha:]]\+ \+//' \
    25342753                        -e '/^UND/d' \
     
    25512770                        -e '/^_Z[[:alpha:]]*[[:digit:]]\+RTC/d' \
    25522771                        -e '/^_Z[[:alpha:]]*[[:digit:]]\+RTC/d' \
    2553                        \
     2772                        \
    25542773                        -e '/^_ZnwjPv/d' \
    25552774                        -e '/^_ZnwmPv/d' \
     
    25622781                       -e '/^_ZNSa.*ElementNode.*/d' \
    25632782                       -e '/^_ZSt.*ElementNode.*/d' \
    2564                        \
     2783                        \
    25652784                        -e '/^_Z[[:digit:]]\+dbus/d' \
    25662785                        -e '/^_Z13RTDBusLoadLibv/d' \
     
    25702789                | $(SED) -nf "$@"
    25712790  endif
    2572         $(call MSG_L1,IPRT: Testing mangling for older gcc...)
    2573         @nm $^  | $(SED) -n \
     2791        $(call MSG_L1,IPRT: Testing mangling using nm...)
     2792        $(QUIET)nm $^  2> /dev/null \
     2793                | $(SED) -n \
    25742794                        -e 's/^[0-9a-f][0-9a-f]* //' \
    25752795                        -e '/^[TUDB] /!d' \
    25762796                        -e 's/^. //' \
     2797                        $(if-expr "$(KBUILD_TARGET)" == "darwin" || "$(KBUILD_TARGET)" == "os2" || "$(KBUILD_TARGET).$(KBUILD_TARGET_ARCH)" == "win.x86", \
     2798                       -e 's/^_//',) \
    25772799                        \
    25782800                        -e '/^g_cchrt/d'\
     
    25862808                        -e '/^g_enmProcessPriority/d'\
    25872809                        -e '/^g_hDbgModStrCache/d'\
     2810                        -e '/^g_pfnR0Darwin/d'\
     2811                        -e '/^g_pDarwinLockGroup/d'\
    25882812                        \
    25892813                        -e '/^RTDBusLoadLib/d' \
     
    26112835include $(FILE_KBUILD_SUB_FOOTER)
    26122836
     2837
     2838#
     2839# Aliases for code templates.
     2840#
     2841rsa-template.o rsa-template.obj: rsa-core.o rsa-asn1-decoder.o rsa-sanity.o rsa-init.o
     2842taf-template.o taf-template.obj: taf-core.o taf-asn1-decoder.o taf-sanity.o taf-init.o
     2843x509-template.o x509-template.obj: x509-core.o x509-asn1-decoder.o x509-sanity.o x509-init.o
     2844pkcs7-template.o pkcs7-template.obj: pkcs7-core.o pkcs7-asn1-decoder.o pkcs7-sanity.o pkcs7-init.o
     2845
  • trunk/src/VBox/Runtime/common/err/errinfo.cpp

    r44529 r51770  
    11/* $Id$ */
    22/** @file
    3  * IPRT - Error Info.
     3 * IPRT - Error Info, Setters.
    44 */
    55
    66/*
    7  * Copyright (C) 2010-2012 Oracle Corporation
     7 * Copyright (C) 2010-2014 Oracle Corporation
    88 *
    99 * This file is part of VirtualBox Open Source Edition (OSE), as
     
    3333
    3434#include <iprt/assert.h>
    35 #include <iprt/mem.h>
    3635#include <iprt/string.h>
    3736
    3837
    39 
    40 RTDECL(PRTERRINFO)  RTErrInfoAlloc(size_t cbMsg)
    41 {
    42     PRTERRINFO pErrInfo;
    43     RTErrInfoAllocEx(cbMsg, &pErrInfo);
    44     return pErrInfo;
    45 }
    46 
    47 
    48 RTDECL(int)         RTErrInfoAllocEx(size_t cbMsg, PRTERRINFO *ppErrInfo)
    49 {
    50     if (cbMsg == 0)
    51         cbMsg = _4K;
    52     else
    53         cbMsg = RT_ALIGN_Z(cbMsg, 256);
    54 
    55     PRTERRINFO pErrInfo;
    56     *ppErrInfo = pErrInfo = (PRTERRINFO)RTMemTmpAlloc(sizeof(*pErrInfo) + cbMsg);
    57     if (RT_UNLIKELY(!pErrInfo))
    58         return VERR_NO_TMP_MEMORY;
    59 
    60     RTErrInfoInit(pErrInfo, (char *)(pErrInfo + 1), cbMsg);
    61     pErrInfo->fFlags = RTERRINFO_FLAGS_T_ALLOC | RTERRINFO_FLAGS_MAGIC;
    62     return VINF_SUCCESS;
    63 }
    64 
    65 
    66 RTDECL(void)        RTErrInfoFree(PRTERRINFO pErrInfo)
    67 {
    68     RTMemTmpFree(pErrInfo);
    69 }
    70 
    71 
    72 RTDECL(int)         RTErrInfoSet(PRTERRINFO pErrInfo, int rc, const char *pszMsg)
     38RTDECL(int) RTErrInfoSet(PRTERRINFO pErrInfo, int rc, const char *pszMsg)
    7339{
    7440    if (pErrInfo)
     
    8551
    8652
    87 RTDECL(int)         RTErrInfoSetF(PRTERRINFO pErrInfo, int rc, const char *pszFormat, ...)
     53RTDECL(int) RTErrInfoSetF(PRTERRINFO pErrInfo, int rc, const char *pszFormat, ...)
    8854{
    8955    va_list va;
     
    9561
    9662
    97 RTDECL(int)         RTErrInfoSetV(PRTERRINFO pErrInfo, int rc, const char *pszFormat, va_list va)
     63RTDECL(int) RTErrInfoSetV(PRTERRINFO pErrInfo, int rc, const char *pszFormat, va_list va)
    9864{
    9965    if (pErrInfo)
     
    10975}
    11076
     77
     78RTDECL(int) RTErrInfoAdd(PRTERRINFO pErrInfo, int rc, const char *pszMsg)
     79{
     80    if (pErrInfo)
     81    {
     82        AssertPtr(pErrInfo);
     83        if (pErrInfo->fFlags & RTERRINFO_FLAGS_SET)
     84            RTStrCat(pErrInfo->pszMsg, pErrInfo->cbMsg, pszMsg);
     85        else
     86        {
     87            while (*pszMsg == ' ')
     88                pszMsg++;
     89            return RTErrInfoSet(pErrInfo, rc, pszMsg);
     90        }
     91    }
     92    return rc;
     93}
     94
     95
     96RTDECL(int) RTErrInfoAddF(PRTERRINFO pErrInfo, int rc, const char *pszFormat, ...)
     97{
     98    va_list va;
     99    va_start(va, pszFormat);
     100    RTErrInfoAddV(pErrInfo, rc, pszFormat, va);
     101    va_end(va);
     102    return rc;
     103}
     104
     105
     106RTDECL(int) RTErrInfoAddV(PRTERRINFO pErrInfo, int rc, const char *pszFormat, va_list va)
     107{
     108    if (pErrInfo)
     109    {
     110        AssertPtr(pErrInfo);
     111        Assert((pErrInfo->fFlags & RTERRINFO_FLAGS_MAGIC_MASK) == RTERRINFO_FLAGS_MAGIC);
     112        if (pErrInfo->fFlags & RTERRINFO_FLAGS_SET)
     113        {
     114            char *pszOut = (char *)memchr(pErrInfo->pszMsg, '\0', pErrInfo->cbMsg - 2);
     115            if (pszOut)
     116                RTStrPrintfV(pszOut, &pErrInfo->pszMsg[pErrInfo->cbMsg] - pszOut, pszFormat, va);
     117        }
     118        else
     119        {
     120            while (*pszFormat == ' ')
     121                pszFormat++;
     122            return RTErrInfoSetV(pErrInfo, rc, pszFormat, va);
     123        }
     124    }
     125    return rc;
     126}
     127
  • trunk/src/VBox/Runtime/common/err/errmsg.cpp

    r48935 r51770  
    4646static const RTSTATUSMSG  g_aStatusMsgs[] =
    4747{
    48 #include "errmsgdata.h"
     48#ifndef IPRT_NO_ERROR_DATA
     49# include "errmsgdata.h"
     50#else
     51    { "Success.", "Success.", "VINF_SUCCESS", 0 },
     52#endif
    4953    { NULL, NULL, NULL, 0 }
    5054};
     
    7781    unsigned iFound = ~0;
    7882    unsigned i;
    79     for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs); i++)
     83    for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs) - 1; i++)
    8084    {
    8185        if (g_aStatusMsgs[i].iCode == rc)
     
    105109     */
    106110    int iMsg = ASMAtomicXchgU32(&g_iUnknownMsgs, (g_iUnknownMsgs + 1) % RT_ELEMENTS(g_aUnknownMsgs));
    107     RTStrPrintf(&g_aszUnknownStr[iMsg][0], sizeof(g_aszUnknownStr[iMsg]), "Unknown Status 0x%X", rc);
     111    RTStrPrintf(&g_aszUnknownStr[iMsg][0], sizeof(g_aszUnknownStr[iMsg]), "Unknown Status %d (%#x)", rc, rc);
    108112    return &g_aUnknownMsgs[iMsg];
    109113}
  • trunk/src/VBox/Runtime/common/ldr/Makefile.kup

    r5430 r51770  
     1
  • trunk/src/VBox/Runtime/common/ldr/ldr.cpp

    r49044 r51770  
    3939#include <iprt/log.h>
    4040#include "internal/ldr.h"
    41 
    42 
    43 RTDECL(bool) RTLdrIsLoadable(const char *pszFilename)
    44 {
    45     /*
    46      * Try to load the library.
    47      */
    48     RTLDRMOD hLib;
    49     int rc = RTLdrLoad(pszFilename, &hLib);
    50     if (RT_SUCCESS(rc))
    51     {
    52         RTLdrClose(hLib);
    53         return true;
    54     }
    55     return false;
    56 }
    57 RT_EXPORT_SYMBOL(RTLdrIsLoadable);
    5841
    5942
  • trunk/src/VBox/Runtime/common/ldr/ldrELF.cpp

    r48935 r51770  
    117117 * @param   enmArch     Architecture specifier.
    118118 * @param   phLdrMod    Where to store the handle.
     119 * @param   pErrInfo    Where to return extended error information. Optional.
    119120 */
    120 int rtldrELFOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod)
     121int rtldrELFOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
    121122{
    122123    const char *pszLogName = pReader->pfnLogName(pReader); NOREF(pszLogName);
  • trunk/src/VBox/Runtime/common/ldr/ldrELFRelocatable.cpp.h

    r49044 r51770  
    14021402    RTLDRELF_NAME(ReadDbgInfo),
    14031403    NULL /*pfnQueryProp*/,
     1404    NULL /*pfnVerifySignature*/,
     1405    NULL /*pfnHashImage*/,
    14041406    42
    14051407};
  • trunk/src/VBox/Runtime/common/ldr/ldrEx.cpp

    r49044 r51770  
    3333#include "internal/iprt.h"
    3434
    35 #include <iprt/alloc.h>
    3635#include <iprt/assert.h>
     36#include <iprt/err.h>
    3737#include <iprt/log.h>
     38#include <iprt/md5.h>
     39#include <iprt/mem.h>
     40#include <iprt/sha.h>
    3841#include <iprt/string.h>
    39 #include <iprt/err.h>
    4042#include "internal/ldr.h"
    4143#include "internal/ldrMZ.h"
    4244
    43 
    44 /**
    45  * Open part with reader.
    46  *
    47  * @returns iprt status code.
    48  * @param   pReader     The loader reader instance which will provide the raw image bits.
    49  * @param   fFlags      Reserved, MBZ.
    50  * @param   enmArch     Architecture specifier.
    51  * @param   phMod       Where to store the handle.
    52  */
    53 int rtldrOpenWithReader(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phMod)
    54 {
     45#ifdef LDR_ONLY_PE
     46# undef LDR_WITH_PE
     47# undef LDR_WITH_KLDR
     48# undef LDR_WITH_ELF
     49# undef LDR_WITH_LX
     50# undef LDR_WITH_LE
     51# undef LDR_WITH_NE
     52# undef LDR_WITH_MZ
     53# undef LDR_WITH_AOUT
     54# define LDR_WITH_PE
     55#endif
     56
     57
     58RTDECL(int) RTLdrOpenWithReader(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phMod, PRTERRINFO pErrInfo)
     59{
     60    /*
     61     * Resolve RTLDRARCH_HOST.
     62     */
     63    if (enmArch == RTLDRARCH_HOST)
     64#if   defined(RT_ARCH_AMD64)
     65        enmArch = RTLDRARCH_AMD64;
     66#elif defined(RT_ARCH_X86)
     67        enmArch = RTLDRARCH_X86_32;
     68#else
     69        enmArch = RTLDRARCH_WHATEVER;
     70#endif
     71
    5572    /*
    5673     * Read and verify the file signature.
     
    105122    if (uSign.u32 == IMAGE_NT_SIGNATURE)
    106123#ifdef LDR_WITH_PE
    107         rc = rtldrPEOpen(pReader, fFlags, enmArch, offHdr, phMod);
     124        rc = rtldrPEOpen(pReader, fFlags, enmArch, offHdr, phMod, pErrInfo);
    108125#else
    109126        rc = VERR_PE_EXE_NOT_SUPPORTED;
     
    111128    else if (uSign.u32 == IMAGE_ELF_SIGNATURE)
    112129#if defined(LDR_WITH_ELF)
    113         rc = rtldrELFOpen(pReader, fFlags, enmArch, phMod);
     130        rc = rtldrELFOpen(pReader, fFlags, enmArch, phMod, pErrInfo);
    114131#else
    115132        rc = VERR_ELF_EXE_NOT_SUPPORTED;
     
    117134    else if (uSign.au16[0] == IMAGE_LX_SIGNATURE)
    118135#ifdef LDR_WITH_LX
    119         rc = rtldrLXOpen(pReader, fFlags, enmArch, offHdr, phMod);
     136        rc = rtldrLXOpen(pReader, fFlags, enmArch, offHdr, phMod, pErrInfo);
    120137#else
    121138        rc = VERR_LX_EXE_NOT_SUPPORTED;
     
    123140    else if (uSign.au16[0] == IMAGE_LE_SIGNATURE)
    124141#ifdef LDR_WITH_LE
    125         rc = rtldrLEOpen(pReader, fFlags, enmArch, phMod);
     142        rc = rtldrLEOpen(pReader, fFlags, enmArch, phMod, pErrInfo);
    126143#else
    127144        rc = VERR_LE_EXE_NOT_SUPPORTED;
     
    129146    else if (uSign.au16[0] == IMAGE_NE_SIGNATURE)
    130147#ifdef LDR_WITH_NE
    131         rc = rtldrNEOpen(pReader, fFlags, enmArch, phMod);
     148        rc = rtldrNEOpen(pReader, fFlags, enmArch, phMod, pErrInfo);
    132149#else
    133150        rc = VERR_NE_EXE_NOT_SUPPORTED;
     
    135152    else if (uSign.au16[0] == IMAGE_DOS_SIGNATURE)
    136153#ifdef LDR_WITH_MZ
    137         rc = rtldrMZOpen(pReader, fFlags, enmArch, phMod);
     154        rc = rtldrMZOpen(pReader, fFlags, enmArch, phMod, pErrInfo);
    138155#else
    139156        rc = VERR_MZ_EXE_NOT_SUPPORTED;
     
    143160             0)
    144161#ifdef LDR_WITH_AOUT
    145         rc = rtldrAOUTOpen(pReader, fFlags, enmArch, phMod);
     162        rc = rtldrAOUTOpen(pReader, fFlags, enmArch, phMod, pErrInfo);
    146163#else
    147164        rc = VERR_AOUT_EXE_NOT_SUPPORTED;
     
    158175    /* Try kLdr if it's a format we don't recognize. */
    159176    if (rc <= VERR_INVALID_EXE_SIGNATURE && rc > VERR_BAD_EXE_FORMAT)
    160         rc = rtldrkLdrOpen(pReader, fFlags, enmArch, phMod);
     177    {
     178        int rc2 = rtldrkLdrOpen(pReader, fFlags, enmArch, phMod, pErrInfo);
     179        if (rc2 == VERR_MZ_EXE_NOT_SUPPORTED) /* Quick fix for bad return code. */
     180            rc = rc;
     181    }
    161182#endif
    162183
     
    542563RTDECL(int) RTLdrQueryProp(RTLDRMOD hLdrMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf)
    543564{
     565    return RTLdrQueryPropEx(hLdrMod, enmProp, pvBuf, cbBuf, NULL);
     566}
     567RT_EXPORT_SYMBOL(RTLdrQueryProp);
     568
     569
     570RTDECL(int) RTLdrQueryPropEx(RTLDRMOD hLdrMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf, size_t *pcbRet)
     571{
    544572    AssertMsgReturn(rtldrIsValid(hLdrMod), ("hLdrMod=%p\n", hLdrMod), RTLDRENDIAN_INVALID);
    545573    PRTLDRMODINTERNAL pMod = (PRTLDRMODINTERNAL)hLdrMod;
    546574
     575    AssertPtrNullReturn(pcbRet, VERR_INVALID_POINTER);
     576    size_t cbRet;
     577    if (!pcbRet)
     578        pcbRet = &cbRet;
     579
    547580    /*
    548581     * Do some pre screening of the input
     
    551584    {
    552585        case RTLDRPROP_UUID:
     586            *pcbRet = sizeof(RTUUID);
    553587            AssertReturn(cbBuf == sizeof(RTUUID), VERR_INVALID_PARAMETER);
    554588            break;
    555589        case RTLDRPROP_TIMESTAMP_SECONDS:
     590            *pcbRet = sizeof(int64_t);
    556591            AssertReturn(cbBuf == sizeof(int32_t) || cbBuf == sizeof(int64_t), VERR_INVALID_PARAMETER);
    557592            break;
     593        case RTLDRPROP_IS_SIGNED:
     594            *pcbRet = sizeof(bool);
     595            AssertReturn(cbBuf == sizeof(bool), VERR_INVALID_PARAMETER);
     596            break;
     597        case RTLDRPROP_PKCS7_SIGNED_DATA:
     598            *pcbRet = 0;
     599            break;
     600        case RTLDRPROP_SIGNATURE_CHECKS_ENFORCED:
     601            *pcbRet = sizeof(bool);
     602            AssertReturn(cbBuf == sizeof(bool), VERR_INVALID_PARAMETER);
     603            break;
     604
    558605        default:
    559606            AssertFailedReturn(VERR_INVALID_FUNCTION);
     
    566613    if (!pMod->pOps->pfnQueryProp)
    567614        return VERR_NOT_SUPPORTED;
    568     return pMod->pOps->pfnQueryProp(pMod, enmProp, pvBuf, cbBuf);
    569 }
    570 RT_EXPORT_SYMBOL(RTLdrQueryProp);
     615    return pMod->pOps->pfnQueryProp(pMod, enmProp, pvBuf, cbBuf, pcbRet);
     616}
     617RT_EXPORT_SYMBOL(RTLdrQueryPropEx);
     618
     619
     620RTDECL(int) RTLdrVerifySignature(RTLDRMOD hLdrMod, PFNRTLDRVALIDATESIGNEDDATA pfnCallback, void *pvUser, PRTERRINFO pErrInfo)
     621{
     622    AssertMsgReturn(rtldrIsValid(hLdrMod), ("hLdrMod=%p\n", hLdrMod), VERR_INVALID_HANDLE);
     623    PRTLDRMODINTERNAL pMod = (PRTLDRMODINTERNAL)hLdrMod;
     624    AssertPtrReturn(pfnCallback, VERR_INVALID_POINTER);
     625
     626    /*
     627     * Call the image specific worker, if there is one.
     628     */
     629    if (!pMod->pOps->pfnVerifySignature)
     630        return VERR_NOT_SUPPORTED;
     631    return pMod->pOps->pfnVerifySignature(pMod, pfnCallback, pvUser, pErrInfo);
     632}
     633RT_EXPORT_SYMBOL(RTLdrVerifySignature);
     634
     635
     636RTDECL(int) RTLdrHashImage(RTLDRMOD hLdrMod, RTDIGESTTYPE enmDigest, char *pszDigest, size_t cbDigest)
     637{
     638    AssertMsgReturn(rtldrIsValid(hLdrMod), ("hLdrMod=%p\n", hLdrMod), VERR_INVALID_HANDLE);
     639    PRTLDRMODINTERNAL pMod = (PRTLDRMODINTERNAL)hLdrMod;
     640
     641    /*
     642     * Make sure there is sufficient space for the wanted digest and that
     643     * it's supported.
     644     */
     645    switch (enmDigest)
     646    {
     647        case RTDIGESTTYPE_MD5:      AssertReturn(cbDigest >= RTMD5_DIGEST_LEN    + 1, VERR_BUFFER_OVERFLOW); break;
     648        case RTDIGESTTYPE_SHA1:     AssertReturn(cbDigest >= RTSHA1_DIGEST_LEN   + 1, VERR_BUFFER_OVERFLOW); break;
     649        case RTDIGESTTYPE_SHA256:   AssertReturn(cbDigest >= RTSHA256_DIGEST_LEN + 1, VERR_BUFFER_OVERFLOW); break;
     650        case RTDIGESTTYPE_SHA512:   AssertReturn(cbDigest >= RTSHA512_DIGEST_LEN + 1, VERR_BUFFER_OVERFLOW); break;
     651        default:
     652            if (enmDigest > RTDIGESTTYPE_INVALID && enmDigest < RTDIGESTTYPE_END)
     653                return VERR_NOT_SUPPORTED;
     654            AssertFailedReturn(VERR_INVALID_PARAMETER);
     655    }
     656    AssertPtrReturn(pszDigest, VERR_INVALID_POINTER);
     657
     658    /*
     659     * Call the image specific worker, if there is one.
     660     */
     661    if (!pMod->pOps->pfnHashImage)
     662        return VERR_NOT_SUPPORTED;
     663    return pMod->pOps->pfnHashImage(pMod, enmDigest, pszDigest, cbDigest);
     664}
     665RT_EXPORT_SYMBOL(RTLdrHashImage);
    571666
    572667
  • trunk/src/VBox/Runtime/common/ldr/ldrFile.cpp

    r48935 r51770  
    218218            if (RT_SUCCESS(rc))
    219219            {
     220                pFileReader->Core.uMagic     = RTLDRREADER_MAGIC;
    220221                pFileReader->Core.pfnRead    = rtldrFileRead;
    221222                pFileReader->Core.pfnTell    = rtldrFileTell;
     
    258259
    259260    /*
    260      * Resolve RTLDRARCH_HOST.
    261      */
    262     if (enmArch == RTLDRARCH_HOST)
    263 #if   defined(RT_ARCH_AMD64)
    264         enmArch = RTLDRARCH_AMD64;
    265 #elif defined(RT_ARCH_X86)
    266         enmArch = RTLDRARCH_X86_32;
    267 #else
    268         enmArch = RTLDRARCH_WHATEVER;
    269 #endif
    270 
    271     /*
    272261     * Create file reader & invoke worker which identifies and calls the image interpreter.
    273262     */
     
    276265    if (RT_SUCCESS(rc))
    277266    {
    278         rc = rtldrOpenWithReader(pReader, fFlags, enmArch, phLdrMod);
     267        rc = RTLdrOpenWithReader(pReader, fFlags, enmArch, phLdrMod, NULL);
    279268        if (RT_SUCCESS(rc))
    280269        {
     
    309298
    310299    /*
    311      * Resolve RTLDRARCH_HOST.
    312      */
    313     if (enmArch == RTLDRARCH_HOST)
    314 # if   defined(RT_ARCH_AMD64)
    315         enmArch = RTLDRARCH_AMD64;
    316 # elif defined(RT_ARCH_X86)
    317         enmArch = RTLDRARCH_X86_32;
    318 # else
    319         enmArch = RTLDRARCH_WHATEVER;
    320 # endif
    321 
    322     /*
    323300     * Create file reader & invoke worker which identifies and calls the image interpreter.
    324301     */
     
    327304    if (RT_SUCCESS(rc))
    328305    {
    329         rc = rtldrkLdrOpen(pReader, fFlags, enmArch, phLdrMod);
     306        rc = rtldrkLdrOpen(pReader, fFlags, enmArch, phLdrMod, NULL);
    330307        if (RT_SUCCESS(rc))
    331308        {
  • trunk/src/VBox/Runtime/common/ldr/ldrMemory.cpp

    r51519 r51770  
    244244        pThis->pvMapping    = NULL;
    245245        pThis->cMappings    = 0;
    246         pThis->Core.pszName    = "rdrmem";
     246        pThis->Core.uMagic     = RTLDRREADER_MAGIC;
    247247        pThis->Core.pfnRead    = rtldrRdrMem_Read;
    248248        pThis->Core.pfnTell    = rtldrRdrMem_Tell;
     
    305305    if (RT_SUCCESS(rc))
    306306    {
    307         rc = rtldrOpenWithReader(pReader, fFlags, enmArch, phLdrMod);
     307        rc = RTLdrOpenWithReader(pReader, fFlags, enmArch, phLdrMod, NULL);
    308308        if (RT_SUCCESS(rc))
    309309        {
  • trunk/src/VBox/Runtime/common/ldr/ldrNative.cpp

    r49044 r51770  
    7171    rtldrNativeEnumSymbols,
    7272    /* ext: */
     73    NULL,
     74    NULL,
    7375    NULL,
    7476    NULL,
     
    319321RT_EXPORT_SYMBOL(RTLdrGetNativeHandle);
    320322
     323
     324RTDECL(bool) RTLdrIsLoadable(const char *pszFilename)
     325{
     326    /*
     327     * Try to load the library.
     328     */
     329    RTLDRMOD hLib;
     330    int rc = RTLdrLoad(pszFilename, &hLib);
     331    if (RT_SUCCESS(rc))
     332    {
     333        RTLdrClose(hLib);
     334        return true;
     335    }
     336    return false;
     337}
     338RT_EXPORT_SYMBOL(RTLdrIsLoadable);
     339
  • trunk/src/VBox/Runtime/common/ldr/ldrPE.cpp

    r49044 r51770  
    3333#include "internal/iprt.h"
    3434
    35 #include <iprt/alloc.h>
    3635#include <iprt/assert.h>
     36#include <iprt/asm.h>
     37#include <iprt/err.h>
    3738#include <iprt/log.h>
     39#include <iprt/md5.h>
     40#include <iprt/mem.h>
    3841#include <iprt/path.h>
     42#include <iprt/sha.h>
    3943#include <iprt/string.h>
    40 #include <iprt/err.h>
     44#ifndef IPRT_WITHOUT_LDR_VERIFY
     45# include <iprt/crypto/pkcs7.h>
     46# include <iprt/crypto/spc.h>
     47# include <iprt/crypto/x509.h>
     48#endif
    4149#include <iprt/formats/codeview.h>
    4250#include "internal/ldrPE.h"
     
    5361 */
    5462#define PE_RVA2TYPE(pvBits, rva, type)  ((type) ((uintptr_t)pvBits + (uintptr_t)(rva)) )
     63
     64/** The max size of the security directory. */
     65#ifdef IN_RING3
     66# define RTLDRMODPE_MAX_SECURITY_DIR_SIZE   _4M
     67#else
     68# define RTLDRMODPE_MAX_SECURITY_DIR_SIZE   _1M
     69#endif
    5570
    5671
     
    92107    /** The image timestamp. */
    93108    uint32_t                uTimestamp;
     109    /** Set if the image is 64-bit, clear if 32-bit. */
     110    bool                    f64Bit;
    94111    /** The import data directory entry. */
    95112    IMAGE_DATA_DIRECTORY    ImportDir;
     
    100117    /** The debug directory entry. */
    101118    IMAGE_DATA_DIRECTORY    DebugDir;
    102 } RTLDRMODPE, *PRTLDRMODPE;
     119    /** The security directory entry. */
     120    IMAGE_DATA_DIRECTORY    SecurityDir;
     121
     122    /** Offset of the first PKCS \#7 SignedData signature if present. */
     123    uint32_t                offPkcs7SignedData;
     124    /** Size of the first PKCS \#7 SignedData. */
     125    uint32_t                cbPkcs7SignedData;
     126
     127    /** Copy of the optional header field DllCharacteristics. */
     128    uint16_t                fDllCharacteristics;
     129} RTLDRMODPE;
     130/** Pointer to the instance data for a PE loader module. */
     131typedef RTLDRMODPE *PRTLDRMODPE;
     132
    103133
    104134/**
     
    132162
    133163
     164/**
     165 * PE hash context union.
     166 */
     167typedef union RTLDRPEHASHCTXUNION
     168{
     169    RTSHA512CONTEXT Sha512;
     170    RTSHA256CONTEXT Sha256;
     171    RTSHA1CONTEXT   Sha1;
     172    RTMD5CONTEXT    Md5;
     173} RTLDRPEHASHCTXUNION;
     174/** Pointer to a PE hash context union. */
     175typedef RTLDRPEHASHCTXUNION *PRTLDRPEHASHCTXUNION;
     176
     177
     178/**
     179 * PE hash digests
     180 */
     181typedef union RTLDRPEHASHRESUNION
     182{
     183    uint8_t abSha512[RTSHA512_HASH_SIZE];
     184    uint8_t abSha256[RTSHA256_HASH_SIZE];
     185    uint8_t abSha1[RTSHA1_HASH_SIZE];
     186    uint8_t abMd5[RTMD5_HASH_SIZE];
     187} RTLDRPEHASHRESUNION;
     188/** Pointer to a PE hash work set. */
     189typedef RTLDRPEHASHRESUNION *PRTLDRPEHASHRESUNION;
     190
     191/**
     192 * Special places to watch out for when hashing a PE image.
     193 */
     194typedef struct RTLDRPEHASHSPECIALS
     195{
     196    uint32_t    cbToHash;
     197    uint32_t    offCksum;
     198    uint32_t    cbCksum;
     199    uint32_t    offSecDir;
     200    uint32_t    cbSecDir;
     201    uint32_t    offEndSpecial;
     202} RTLDRPEHASHSPECIALS;
     203/** Pointer to the structure with the special hash places. */
     204typedef RTLDRPEHASHSPECIALS *PRTLDRPEHASHSPECIALS;
     205
     206
     207#ifndef IPRT_WITHOUT_LDR_VERIFY
     208/**
     209 * Parsed signature data.
     210 */
     211typedef struct RTLDRPESIGNATURE
     212{
     213    /** The outer content info wrapper. */
     214    RTCRPKCS7CONTENTINFO        ContentInfo;
     215    /** Pointer to the decoded SignedData inside the ContentInfo member. */
     216    PRTCRPKCS7SIGNEDDATA        pSignedData;
     217    /** Pointer to the indirect data content. */
     218    PRTCRSPCINDIRECTDATACONTENT pIndData;
     219    /** The digest type employed by the signature. */
     220    RTDIGESTTYPE                enmDigest;
     221
     222    /** Pointer to the raw signatures.  This is allocated in the continuation of
     223     * this structure to keep things simple.  The size is given by  the security
     224     * export directory. */
     225    WIN_CERTIFICATE const      *pRawData;
     226
     227    /** Hash scratch data. */
     228    RTLDRPEHASHCTXUNION         HashCtx;
     229    /** Hash result. */
     230    RTLDRPEHASHRESUNION         HashRes;
     231} RTLDRPESIGNATURE;
     232/** Pointed to SigneData parsing stat and output. */
     233typedef RTLDRPESIGNATURE *PRTLDRPESIGNATURE;
     234#endif
     235
     236
    134237/*******************************************************************************
    135238*   Internal Functions                                                         *
     
    251354        {
    252355            if ((RTFOFF)offFile + cbToRead > cbFile)
    253                 cbToRead = cbFile - (RTFOFF)offFile;
     356                cbToRead = (uint32_t)(cbFile - (RTFOFF)offFile);
    254357            int rc = pThis->Core.pReader->pfnRead(pThis->Core.pReader, pbMem, cbToRead, offFile);
    255358            if (RT_FAILURE(rc))
     
    331434    if (uRva == NIL_RTLDRADDR || uRva > pThis->cbImage)
    332435    {
    333         if (offFile < 0)
     436        if (offFile < 0 || offFile >= UINT32_MAX)
    334437            return VERR_INVALID_PARAMETER;
    335         return rtldrPEReadPartFromFile(pThis, offFile, cbMem, ppvMem);
    336     }
    337     return rtldrPEReadPartByRva(pThis, pvBits, uRva, cbMem, ppvMem);
     438        return rtldrPEReadPartFromFile(pThis, (uint32_t)offFile, cbMem, ppvMem);
     439    }
     440    return rtldrPEReadPartByRva(pThis, pvBits, (uint32_t)uRva, cbMem, ppvMem);
    338441}
    339442
     
    549652                rc = VERR_BAD_EXE_FORMAT;
    550653            }
    551             pFirstThunk->u1.Function = Value;
     654            pFirstThunk->u1.Function = (uint32_t)Value;
    552655            if (pFirstThunk->u1.Function != Value)
    553656            {
     
    664767        /* Some bound checking just to be sure it works... */
    665768        if ((uintptr_t)pbr - (uintptr_t)pBaseRelocs + pbr->SizeOfBlock > cbBaseRelocs)
    666             cRelocations = (((uintptr_t)pBaseRelocs + cbBaseRelocs) - (uintptr_t)pbr - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(uint16_t);
     769            cRelocations = (uint32_t)(  (((uintptr_t)pBaseRelocs + cbBaseRelocs) - (uintptr_t)pbr - sizeof(IMAGE_BASE_RELOCATION))
     770                                      / sizeof(uint16_t) );
    667771
    668772        /*
     
    692796            {
    693797                case IMAGE_REL_BASED_HIGHLOW:   /* 32-bit, add delta. */
    694                     *u.pu32 += uDelta;
     798                    *u.pu32 += (uint32_t)uDelta;
    695799                    break;
    696800                case IMAGE_REL_BASED_DIR64:     /* 64-bit, add delta. */
     
    717821                    pwoffFixup++;
    718822                    int32_t i32 = (uint32_t)(*u.pu16 << 16) | *pwoffFixup;
    719                     i32 += uDelta;
     823                    i32 += (uint32_t)uDelta;
    720824                    i32 += 0x8000; //??
    721825                    *u.pu16 = (uint16_t)(i32 >> 16);
     
    760864
    761865/** @copydoc RTLDROPS::pfnRelocate. */
    762 static int rtldrPERelocate(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress, RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
     866static DECLCALLBACK(int) rtldrPERelocate(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress, RTUINTPTR OldBaseAddress,
     867                                         PFNRTLDRIMPORT pfnGetImport, void *pvUser)
    763868{
    764869    PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
     
    9261031    if (RT_SUCCESS(rc))
    9271032    {
    928         uintptr_t  uNamePrev = 0;
     1033        uint32_t uNamePrev = 0;
    9291034        for (uint32_t uOrdinal = 0; uOrdinal < cOrdinals; uOrdinal++)
    9301035        {
     
    10631168    uint32_t   *paRVANames = PE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, uint32_t *);
    10641169    uint16_t   *paOrdinals = PE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, uint16_t *);
    1065     uintptr_t   uNamePrev = 0;
     1170    uint32_t    uNamePrev = 0;
    10661171    unsigned    cOrdinals = RT_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions);
    10671172    for (unsigned uOrdinal = 0; uOrdinal < cOrdinals; uOrdinal++)
     
    10741179            const char *pszName = NULL;
    10751180            /* Search from previous + 1 to the end.  */
    1076             unsigned    uName = uNamePrev + 1;
     1181            uint32_t uName = uNamePrev + 1;
    10771182            while (uName < pExpDir->NumberOfNames)
    10781183            {
     
    11471252
    11481253    /*
     1254     * Allocate temporary memory for a path buffer (this code is also compiled
     1255     * and maybe even used in stack starved environments).
     1256     */
     1257    char *pszPath = (char *)RTMemTmpAlloc(RTPATH_MAX);
     1258    if (!pszPath)
     1259        return VERR_NO_TMP_MEMORY;
     1260
     1261    /*
    11491262     * Get the debug directory.
    11501263     */
     
    11561269                                     (void const **)&paDbgDir);
    11571270    if (RT_FAILURE(rcRet))
     1271    {
     1272        RTMemTmpFree(pszPath);
    11581273        return rcRet;
     1274    }
    11591275
    11601276    /*
     
    11701286
    11711287        void const     *pvPart = NULL;
    1172         char            szPath[RTPATH_MAX];
    11731288        RTLDRDBGINFO    DbgInfo;
    11741289        RT_ZERO(DbgInfo.u);
     
    11901305                DbgInfo.u.Cv.uMinorVer  = paDbgDir[i].MinorVersion;
    11911306                DbgInfo.u.Cv.uTimestamp = paDbgDir[i].TimeDateStamp;
    1192                 if (   paDbgDir[i].SizeOfData < sizeof(szPath)
     1307                if (   paDbgDir[i].SizeOfData < RTPATH_MAX
    11931308                    && paDbgDir[i].SizeOfData > 16
    11941309                    && (   DbgInfo.LinkAddress != NIL_RTLDRADDR
     
    12281343            case IMAGE_DEBUG_TYPE_MISC:
    12291344                DbgInfo.enmType = RTLDRDBGINFOTYPE_UNKNOWN;
    1230                 if (   paDbgDir[i].SizeOfData < sizeof(szPath)
     1345                if (   paDbgDir[i].SizeOfData < RTPATH_MAX
    12311346                    && paDbgDir[i].SizeOfData > RT_UOFFSETOF(IMAGE_DEBUG_MISC, Data))
    12321347                {
     
    12491364                            else
    12501365                            {
    1251                                 char *pszPath = szPath;
    12521366                                rc = RTUtf16ToUtf8Ex((PCRTUTF16)&pMisc->Data[0],
    12531367                                                     (pMisc->Length - RT_OFFSETOF(IMAGE_DEBUG_MISC, Data)) / sizeof(RTUTF16),
    1254                                                      &pszPath, sizeof(szPath), NULL);
     1368                                                     &pszPath, RTPATH_MAX, NULL);
    12551369                                if (RT_SUCCESS(rc))
    1256                                     DbgInfo.pszExtFile = szPath;
     1370                                    DbgInfo.pszExtFile = pszPath;
    12571371                                else
    12581372                                    rcRet = rc; /* continue without a filename. */
     
    12831397           it's probably the current ANSI/Windows code page for the process
    12841398           generating the image anyways.) */
    1285         if (DbgInfo.pszExtFile && DbgInfo.pszExtFile != szPath)
    1286         {
    1287             char *pszPath = szPath;
     1399        if (DbgInfo.pszExtFile && DbgInfo.pszExtFile != pszPath)
     1400        {
    12881401            rc = RTLatin1ToUtf8Ex(DbgInfo.pszExtFile,
    12891402                                  paDbgDir[i].SizeOfData - ((uintptr_t)DbgInfo.pszExtFile - (uintptr_t)pvBits),
    1290                                   &pszPath, sizeof(szPath), NULL);
     1403                                  &pszPath, RTPATH_MAX, NULL);
    12911404            if (RT_FAILURE(rc))
    12921405            {
     
    12961409        }
    12971410        if (DbgInfo.pszExtFile)
    1298             RTPathChangeToUnixSlashes(szPath, true /*fForce*/);
     1411            RTPathChangeToUnixSlashes(pszPath, true /*fForce*/);
    12991412
    13001413        rc = pfnCallback(pMod, &DbgInfo, pvUser);
     
    13081421
    13091422    rtldrPEFreePart(pModPe, pvBits, paDbgDir);
     1423    RTMemTmpFree(pszPath);
    13101424    return rcRet;
    13111425}
     
    14911605
    14921606/** @interface_method_impl{RTLDROPS,pfnQueryProp} */
    1493 static DECLCALLBACK(int) rtldrPE_QueryProp(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf)
     1607static DECLCALLBACK(int) rtldrPE_QueryProp(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf, size_t *pcbRet)
    14941608{
    14951609    PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
     
    14971611    {
    14981612        case RTLDRPROP_TIMESTAMP_SECONDS:
     1613            Assert(*pcbRet == cbBuf);
    14991614            if (cbBuf == sizeof(int32_t))
    15001615                *(int32_t *)pvBuf = pModPe->uTimestamp;
     
    15021617                *(int64_t *)pvBuf = pModPe->uTimestamp;
    15031618            else
    1504                 return VERR_INVALID_PARAMETER;
     1619                AssertFailedReturn(VERR_INTERNAL_ERROR_3);
     1620            break;
     1621
     1622        case RTLDRPROP_IS_SIGNED:
     1623            Assert(cbBuf == sizeof(bool));
     1624            Assert(*pcbRet == cbBuf);
     1625            *(bool *)pvBuf = pModPe->offPkcs7SignedData != 0;
     1626            break;
     1627
     1628        case RTLDRPROP_PKCS7_SIGNED_DATA:
     1629        {
     1630            if (pModPe->cbPkcs7SignedData == 0)
     1631                return VERR_NOT_FOUND;
     1632            Assert(pModPe->offPkcs7SignedData > pModPe->SecurityDir.VirtualAddress);
     1633
     1634            *pcbRet = pModPe->cbPkcs7SignedData;
     1635            if (cbBuf < pModPe->cbPkcs7SignedData)
     1636                return VERR_BUFFER_OVERFLOW;
     1637            return pModPe->Core.pReader->pfnRead(pModPe->Core.pReader, pvBuf, pModPe->cbPkcs7SignedData,
     1638                                                 pModPe->offPkcs7SignedData);
     1639        }
     1640
     1641        case RTLDRPROP_SIGNATURE_CHECKS_ENFORCED:
     1642            Assert(cbBuf == sizeof(bool));
     1643            Assert(*pcbRet == cbBuf);
     1644            *(bool *)pvBuf = pModPe->offPkcs7SignedData > 0
     1645                          && (pModPe->fDllCharacteristics & IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY);
    15051646            break;
    15061647
     
    15121653
    15131654
     1655
     1656/*
     1657 * Lots of Authenticode fun ahead.
     1658 */
     1659
     1660
     1661/**
     1662 * Initializes the hash context.
     1663 *
     1664 * @returns VINF_SUCCESS or VERR_NOT_SUPPORTED.
     1665 * @param   pHashCtx            The hash context union.
     1666 * @param   enmDigest           The hash type we're calculating..
     1667 */
     1668static int rtLdrPE_HashInit(PRTLDRPEHASHCTXUNION pHashCtx, RTDIGESTTYPE enmDigest)
     1669{
     1670    switch (enmDigest)
     1671    {
     1672        case RTDIGESTTYPE_SHA512:  RTSha512Init(&pHashCtx->Sha512); break;
     1673        case RTDIGESTTYPE_SHA256:  RTSha256Init(&pHashCtx->Sha256); break;
     1674        case RTDIGESTTYPE_SHA1:    RTSha1Init(&pHashCtx->Sha1); break;
     1675        case RTDIGESTTYPE_MD5:     RTMd5Init(&pHashCtx->Md5); break;
     1676        default:                   AssertFailedReturn(VERR_NOT_SUPPORTED);
     1677    }
     1678    return VINF_SUCCESS;
     1679}
     1680
     1681
     1682/**
     1683 * Updates the hash with more data.
     1684 *
     1685 * @param   pHashCtx            The hash context union.
     1686 * @param   enmDigest           The hash type we're calculating..
     1687 * @param   pvBuf               Pointer to a buffer with bytes to add to thash.
     1688 * @param   cbBuf               How many bytes to add from @a pvBuf.
     1689 */
     1690static void rtLdrPE_HashUpdate(PRTLDRPEHASHCTXUNION pHashCtx, RTDIGESTTYPE enmDigest, void const *pvBuf, size_t cbBuf)
     1691{
     1692    switch (enmDigest)
     1693    {
     1694        case RTDIGESTTYPE_SHA512:  RTSha512Update(&pHashCtx->Sha512, pvBuf, cbBuf); break;
     1695        case RTDIGESTTYPE_SHA256:  RTSha256Update(&pHashCtx->Sha256, pvBuf, cbBuf); break;
     1696        case RTDIGESTTYPE_SHA1:    RTSha1Update(&pHashCtx->Sha1, pvBuf, cbBuf); break;
     1697        case RTDIGESTTYPE_MD5:     RTMd5Update(&pHashCtx->Md5, pvBuf, cbBuf); break;
     1698        default:                   AssertReleaseFailed();
     1699    }
     1700}
     1701
     1702
     1703/**
     1704 * Finalizes the hash calculations.
     1705 *
     1706 * @param   pHashCtx            The hash context union.
     1707 * @param   enmDigest           The hash type we're calculating..
     1708 * @param   pHashRes            The hash result union.
     1709 */
     1710static void rtLdrPE_HashFinalize(PRTLDRPEHASHCTXUNION pHashCtx, RTDIGESTTYPE enmDigest, PRTLDRPEHASHRESUNION pHashRes)
     1711{
     1712    switch (enmDigest)
     1713    {
     1714        case RTDIGESTTYPE_SHA512:  RTSha512Final(&pHashCtx->Sha512, pHashRes->abSha512); break;
     1715        case RTDIGESTTYPE_SHA256:  RTSha256Final(&pHashCtx->Sha256, pHashRes->abSha256); break;
     1716        case RTDIGESTTYPE_SHA1:    RTSha1Final(&pHashCtx->Sha1, pHashRes->abSha1); break;
     1717        case RTDIGESTTYPE_MD5:     RTMd5Final(pHashRes->abMd5, &pHashCtx->Md5); break;
     1718        default:                   AssertReleaseFailed();
     1719    }
     1720}
     1721
     1722
     1723/**
     1724 * Returns the digest size for the given digest type.
     1725 *
     1726 * @returns Size in bytes.
     1727 * @param   enmDigest           The hash type in question.
     1728 */
     1729static uint32_t rtLdrPE_HashGetHashSize(RTDIGESTTYPE enmDigest)
     1730{
     1731    switch (enmDigest)
     1732    {
     1733        case RTDIGESTTYPE_SHA512:  return RTSHA512_HASH_SIZE;
     1734        case RTDIGESTTYPE_SHA256:  return RTSHA256_HASH_SIZE;
     1735        case RTDIGESTTYPE_SHA1:    return RTSHA1_HASH_SIZE;
     1736        case RTDIGESTTYPE_MD5:     return RTMD5_HASH_SIZE;
     1737        default:                   AssertReleaseFailedReturn(0);
     1738    }
     1739}
     1740
     1741
     1742/**
     1743 * Calculate the special too watch out for when hashing the image.
     1744 *
     1745 * @returns IPRT status code.
     1746 * @param   pModPe              The PE module.
     1747 * @param   pPlaces             The structure where to store the special places.
     1748 * @param   pErrInfo            Optional error info.
     1749 */
     1750static int rtldrPe_CalcSpecialHashPlaces(PRTLDRMODPE pModPe, PRTLDRPEHASHSPECIALS pPlaces, PRTERRINFO pErrInfo)
     1751{
     1752    /*
     1753     * If we're here despite a missing signature, we need to get the file size.
     1754     */
     1755    pPlaces->cbToHash = pModPe->SecurityDir.VirtualAddress;
     1756    if (pPlaces->cbToHash == 0)
     1757    {
     1758        RTFOFF cbFile = pModPe->Core.pReader->pfnSize(pModPe->Core.pReader);
     1759        pPlaces->cbToHash = (uint32_t)cbFile;
     1760        if (pPlaces->cbToHash != (RTFOFF)cbFile)
     1761            return RTErrInfoSetF(pErrInfo, VERR_LDRVI_FILE_LENGTH_ERROR, "File is too large: %RTfoff", cbFile);
     1762    }
     1763
     1764    /*
     1765     * Calculate the special places.
     1766     */
     1767    pPlaces->offCksum       = (uint32_t)pModPe->offNtHdrs
     1768                            + (pModPe->f64Bit
     1769                               ? RT_OFFSETOF(IMAGE_NT_HEADERS64, OptionalHeader.CheckSum)
     1770                               : RT_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader.CheckSum));
     1771    pPlaces->cbCksum        = RT_SIZEOFMEMB(IMAGE_NT_HEADERS32, OptionalHeader.CheckSum);
     1772    pPlaces->offSecDir      = (uint32_t)pModPe->offNtHdrs
     1773                            + (pModPe->f64Bit
     1774                               ? RT_OFFSETOF(IMAGE_NT_HEADERS64, OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY])
     1775                               : RT_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]));
     1776    pPlaces->cbSecDir       = sizeof(IMAGE_DATA_DIRECTORY);
     1777    pPlaces->offEndSpecial  = pPlaces->offSecDir + pPlaces->cbSecDir;
     1778    return VINF_SUCCESS;
     1779}
     1780
     1781
     1782/**
     1783 * Calculates the whole image hash.
     1784 *
     1785 * The Authenticode_PE.docx version 1.0 explains how the hash is calculated,
     1786 * points 8 thru 14 are bogus.  If you study them a little carefully, it is
     1787 * clear that the algorithm will only work if the raw data for the section have
     1788 * no gaps between them or in front of them.  So, this elaborate section sorting
     1789 * by PointerToRawData and working them section by section could simply be
     1790 * replaced by one point:
     1791 *
     1792 *      8. Add all the file content between SizeOfHeaders and the
     1793 *         attribute certificate table to the hash.  Then finalize
     1794 *         the hash.
     1795 *
     1796 * Not sure if Microsoft is screwing with us on purpose here or whether they
     1797 * assigned some of this work to less talented engineers and tech writers.  I
     1798 * love fact that they say it's "simplified" and should yield the correct hash
     1799 * for "almost all" files.  Stupid, Stupid, Microsofties!!
     1800 *
     1801 * My simplified implementation that just hashes the entire file up to the
     1802 * signature or end of the file produces the same SHA1 values as "signtool
     1803 * verify /v" does both for edited executables with gaps between/before/after
     1804 * sections raw data and normal executables without any gaps.
     1805 *
     1806 * @returns IPRT status code.
     1807 * @param   pModPe      The PE module.
     1808 * @param   pvScratch   Scratch buffer.
     1809 * @param   cbScratch   Size of the scratch buffer.
     1810 * @param   enmDigest   The hash digest type we're calculating.
     1811 * @param   pHashCtx    Hash context scratch area.
     1812 * @param   pHashRes    Hash result buffer.
     1813 * @param   pErrInfo    Optional error info buffer.
     1814 */
     1815static int rtldrPE_HashImageCommon(PRTLDRMODPE pModPe, void *pvScratch, uint32_t cbScratch, RTDIGESTTYPE enmDigest,
     1816                                   PRTLDRPEHASHCTXUNION pHashCtx, PRTLDRPEHASHRESUNION pHashRes, PRTERRINFO pErrInfo)
     1817{
     1818    int rc = rtLdrPE_HashInit(pHashCtx, enmDigest);
     1819    if (RT_FAILURE(rc))
     1820        return rc;
     1821
     1822    /*
     1823     * Calculate the special places.
     1824     */
     1825    RTLDRPEHASHSPECIALS SpecialPlaces;
     1826    rc = rtldrPe_CalcSpecialHashPlaces(pModPe, &SpecialPlaces, pErrInfo);
     1827    if (RT_FAILURE(rc))
     1828        return rc;
     1829
     1830    /*
     1831     * Work our way thru the image data.
     1832     */
     1833    uint32_t off = 0;
     1834    while (off < SpecialPlaces.cbToHash)
     1835    {
     1836        uint32_t cbRead = RT_MIN(SpecialPlaces.cbToHash - off, cbScratch);
     1837        uint8_t *pbCur  = (uint8_t *)pvScratch;
     1838        rc = pModPe->Core.pReader->pfnRead(pModPe->Core.pReader, pbCur, cbRead, off);
     1839        if (RT_FAILURE(rc))
     1840            return RTErrInfoSetF(pErrInfo, VERR_LDRVI_READ_ERROR_HASH, "Hash read error at %#x: %Rrc (cbRead=%#zx)",
     1841                                 off, rc, cbRead);
     1842
     1843        if (off < SpecialPlaces.offEndSpecial)
     1844        {
     1845            if (off < SpecialPlaces.offCksum)
     1846            {
     1847                /* Hash everything up to the checksum. */
     1848                uint32_t cbChunk = RT_MIN(SpecialPlaces.offCksum - off, cbRead);
     1849                rtLdrPE_HashUpdate(pHashCtx, enmDigest, pbCur, cbChunk);
     1850                pbCur  += cbChunk;
     1851                cbRead -= cbChunk;
     1852                off    += cbChunk;
     1853            }
     1854
     1855            if (off < SpecialPlaces.offCksum + SpecialPlaces.cbCksum && off >= SpecialPlaces.offCksum)
     1856            {
     1857                /* Skip the checksum */
     1858                uint32_t cbChunk = RT_MIN(SpecialPlaces.offCksum + SpecialPlaces.cbCksum - off, cbRead);
     1859                pbCur  += cbChunk;
     1860                cbRead -= cbChunk;
     1861                off    += cbChunk;
     1862            }
     1863
     1864            if (off < SpecialPlaces.offSecDir && off >= SpecialPlaces.offCksum + SpecialPlaces.cbCksum)
     1865            {
     1866                /* Hash everything between the checksum and the data dir entry. */
     1867                uint32_t cbChunk = RT_MIN(SpecialPlaces.offSecDir - off, cbRead);
     1868                rtLdrPE_HashUpdate(pHashCtx, enmDigest,  pbCur, cbChunk);
     1869                pbCur  += cbChunk;
     1870                cbRead -= cbChunk;
     1871                off    += cbChunk;
     1872            }
     1873
     1874            if (off < SpecialPlaces.offSecDir + SpecialPlaces.cbSecDir && off >= SpecialPlaces.offSecDir)
     1875            {
     1876                /* Skip the security data directory entry. */
     1877                uint32_t cbChunk = RT_MIN(SpecialPlaces.offSecDir + SpecialPlaces.cbSecDir - off, cbRead);
     1878                pbCur  += cbChunk;
     1879                cbRead -= cbChunk;
     1880                off    += cbChunk;
     1881            }
     1882        }
     1883
     1884        rtLdrPE_HashUpdate(pHashCtx, enmDigest, pbCur, cbRead);
     1885
     1886        /* Advance */
     1887        off += cbRead;
     1888    }
     1889
     1890    /*
     1891     * If there isn't a signature, experiments with signtool indicates that we
     1892     * have to zero padd the file size until it's a multiple of 8.  (This is
     1893     * most likely to give 64-bit values in the certificate a natural alignment
     1894     * when memory mapped.)
     1895     */
     1896    if (   pModPe->SecurityDir.Size != SpecialPlaces.cbToHash
     1897        && SpecialPlaces.cbToHash != RT_ALIGN_32(SpecialPlaces.cbToHash, WIN_CERTIFICATE_ALIGNMENT))
     1898    {
     1899        static const uint8_t s_abZeros[WIN_CERTIFICATE_ALIGNMENT] = { 0,0,0,0, 0,0,0,0 };
     1900        rtLdrPE_HashUpdate(pHashCtx, enmDigest, s_abZeros,
     1901                           RT_ALIGN_32(SpecialPlaces.cbToHash, WIN_CERTIFICATE_ALIGNMENT) - SpecialPlaces.cbToHash);
     1902    }
     1903
     1904    /*
     1905     * Done. Finalize the hashes.
     1906     */
     1907    rtLdrPE_HashFinalize(pHashCtx, enmDigest, pHashRes);
     1908    return VINF_SUCCESS;
     1909}
     1910
     1911#ifndef IPRT_WITHOUT_LDR_VERIFY
     1912
     1913/**
     1914 * Verifies image preconditions not checked by the open validation code.
     1915 *
     1916 * @returns IPRT status code.
     1917 * @param   pModPe              The PE module.
     1918 * @param   pErrInfo            Optional error info buffer.
     1919 */
     1920static int rtldrPE_VerifySignatureImagePrecoditions(PRTLDRMODPE pModPe, PRTERRINFO pErrInfo)
     1921{
     1922    /*
     1923     * Validate the sections.  While doing so, track the amount of section raw
     1924     * section data in the file so we can use this to validate the signature
     1925     * table location later.
     1926     */
     1927    uint32_t offNext = pModPe->cbHeaders; /* same */
     1928    for (uint32_t i = 0; i < pModPe->cSections; i++)
     1929        if (pModPe->paSections[i].SizeOfRawData > 0)
     1930        {
     1931            uint64_t offEnd = (uint64_t)pModPe->paSections[i].PointerToRawData + pModPe->paSections[i].SizeOfRawData;
     1932            if (offEnd > offNext)
     1933            {
     1934                if (offEnd >= _2G)
     1935                    return RTErrInfoSetF(pErrInfo, VERR_LDRVI_SECTION_RAW_DATA_VALUES,
     1936                                         "Section %#u specifies file data after 2GB: PointerToRawData=%#x SizeOfRawData=%#x",
     1937                                         i, pModPe->paSections[i].PointerToRawData, pModPe->paSections[i].SizeOfRawData);
     1938                offNext = (uint32_t)offEnd;
     1939            }
     1940        }
     1941    uint32_t offEndOfSectionData = offNext;
     1942
     1943    /*
     1944     * Validate the signature.
     1945     */
     1946    if (!pModPe->SecurityDir.Size)
     1947        return RTErrInfoSet(pErrInfo, VERR_LDRVI_NOT_SIGNED, "Not signed.");
     1948
     1949    uint32_t const offSignature = pModPe->SecurityDir.VirtualAddress;
     1950    uint32_t const cbSignature  = pModPe->SecurityDir.Size;
     1951    if (   cbSignature  <= sizeof(WIN_CERTIFICATE)
     1952        || cbSignature  >= RTLDRMODPE_MAX_SECURITY_DIR_SIZE
     1953        || offSignature >= _2G)
     1954        return RTErrInfoSetF(pErrInfo, VERR_LDRVI_INVALID_SECURITY_DIR_ENTRY,
     1955                             "Invalid security data dir entry: cb=%#x off=%#x", cbSignature, offSignature);
     1956
     1957    if (offSignature < offEndOfSectionData)
     1958        return RTErrInfoSetF(pErrInfo, VERR_LDRVI_INVALID_SECURITY_DIR_ENTRY,
     1959                             "Invalid security data dir entry offset: %#x offEndOfSectionData=%#x",
     1960                             offSignature, offEndOfSectionData);
     1961
     1962    if (RT_ALIGN_32(offSignature, WIN_CERTIFICATE_ALIGNMENT) != offSignature)
     1963        return RTErrInfoSetF(pErrInfo, VERR_LDRVI_INVALID_SECURITY_DIR_ENTRY,
     1964                             "Misaligned security dir entry offset: %#x (alignment=%#x)",
     1965                             offSignature, WIN_CERTIFICATE_ALIGNMENT);
     1966
     1967
     1968    return VINF_SUCCESS;
     1969}
     1970
     1971
     1972/**
     1973 * Reads and checks the raw signature data.
     1974 *
     1975 * @returns IPRT status code.
     1976 * @param   pModPe              The PE module.
     1977 * @param   ppSignature         Where to return the pointer to the parsed
     1978 *                              signature data.  Pass to
     1979 *                              rtldrPE_VerifySignatureDestroy when done.
     1980 * @param   pErrInfo            Optional error info buffer.
     1981 */
     1982static int rtldrPE_VerifySignatureRead(PRTLDRMODPE pModPe, PRTLDRPESIGNATURE *ppSignature, PRTERRINFO pErrInfo)
     1983{
     1984    *ppSignature = NULL;
     1985    AssertReturn(pModPe->SecurityDir.Size > 0, VERR_INTERNAL_ERROR_2);
     1986
     1987    /*
     1988     * Allocate memory for reading and parsing it.
     1989     */
     1990    if (pModPe->SecurityDir.Size >= RTLDRMODPE_MAX_SECURITY_DIR_SIZE)
     1991        return RTErrInfoSetF(pErrInfo, VERR_LDRVI_INVALID_SECURITY_DIR_ENTRY,
     1992                             "Signature directory is to large: %#x", pModPe->SecurityDir.Size);
     1993
     1994    PRTLDRPESIGNATURE pSignature = (PRTLDRPESIGNATURE)RTMemTmpAllocZ(sizeof(*pSignature) + 64 + pModPe->SecurityDir.Size);
     1995    if (!pSignature)
     1996        return RTErrInfoSetF(pErrInfo, VERR_LDRVI_NO_MEMORY_SIGNATURE, "Failed to allocate %zu bytes",
     1997                             sizeof(*pSignature) + 64 + pModPe->SecurityDir.Size);
     1998    pSignature->pRawData = RT_ALIGN_PT(pSignature + 1, 64, WIN_CERTIFICATE const *);
     1999
     2000
     2001    /*
     2002     * Read it.
     2003     */
     2004    int rc = pModPe->Core.pReader->pfnRead(pModPe->Core.pReader, (void *)pSignature->pRawData,
     2005                                           pModPe->SecurityDir.Size, pModPe->SecurityDir.VirtualAddress);
     2006    if (RT_SUCCESS(rc))
     2007    {
     2008        /*
     2009         * Check the table we've read in.
     2010         */
     2011        uint32_t               cbLeft = pModPe->SecurityDir.Size;
     2012        WIN_CERTIFICATE const *pEntry = pSignature->pRawData;
     2013        for (;;)
     2014        {
     2015            if (   cbLeft           < sizeof(*pEntry)
     2016                || pEntry->dwLength > cbLeft
     2017                || pEntry->dwLength < sizeof(*pEntry))
     2018                rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_BAD_CERT_HDR_LENGTH,
     2019                                   "Bad WIN_CERTIFICATE length: %#x  (max %#x, signature=%u)",
     2020                                   pEntry->dwLength, cbLeft, 0);
     2021            else if (pEntry->wRevision != WIN_CERT_REVISION_2_0)
     2022                rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_BAD_CERT_HDR_REVISION,
     2023                                   "Unsupported WIN_CERTIFICATE revision value: %#x (signature=%u)",
     2024                                   pEntry->wRevision, 0);
     2025            else if (pEntry->wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA)
     2026                rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_BAD_CERT_HDR_TYPE,
     2027                                   "Unsupported WIN_CERTIFICATE certificate type: %#x (signature=%u)",
     2028                                   pEntry->wCertificateType, 0);
     2029            else
     2030            {
     2031                /* advance */
     2032                uint32_t cbEntry = RT_ALIGN(pEntry->dwLength, WIN_CERTIFICATE_ALIGNMENT);
     2033                if (cbEntry >= cbLeft)
     2034                    break;
     2035                cbLeft -= cbEntry;
     2036                pEntry = (WIN_CERTIFICATE *)((uintptr_t)pEntry + cbEntry);
     2037
     2038                /* For now, only one entry is supported. */
     2039                rc = RTErrInfoSet(pErrInfo, VERR_LDRVI_BAD_CERT_MULTIPLE, "Multiple WIN_CERTIFICATE entries are not supported.");
     2040            }
     2041            break;
     2042        }
     2043        if (RT_SUCCESS(rc))
     2044        {
     2045            *ppSignature = pSignature;
     2046            return VINF_SUCCESS;
     2047        }
     2048    }
     2049    else
     2050        rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_READ_ERROR_SIGNATURE, "Signature read error: %Rrc", rc);
     2051    RTMemTmpFree(pSignature);
     2052    return rc;
     2053}
     2054
     2055
     2056/**
     2057 * Destroys the parsed signature.
     2058 *
     2059 * @param   pModPe              The PE module.
     2060 * @param   pSignature          The signature data to destroy.
     2061 */
     2062static void rtldrPE_VerifySignatureDestroy(PRTLDRMODPE pModPe, PRTLDRPESIGNATURE pSignature)
     2063{
     2064    RTCrPkcs7ContentInfo_Delete(&pSignature->ContentInfo);
     2065    RTMemTmpFree(pSignature);
     2066}
     2067
     2068
     2069/**
     2070 * Decodes the raw signature.
     2071 *
     2072 * @returns IPRT status code.
     2073 * @param   pModPe              The PE module.
     2074 * @param   pSignature          The signature data.
     2075 * @param   pErrInfo            Optional error info buffer.
     2076 */
     2077static int rtldrPE_VerifySignatureDecode(PRTLDRMODPE pModPe, PRTLDRPESIGNATURE pSignature, PRTERRINFO pErrInfo)
     2078{
     2079    WIN_CERTIFICATE const  *pEntry = pSignature->pRawData;
     2080    AssertReturn(pEntry->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA, VERR_INTERNAL_ERROR_2);
     2081    AssertReturn(pEntry->wRevision        == WIN_CERT_REVISION_2_0, VERR_INTERNAL_ERROR_2);
     2082
     2083    RTASN1CURSORPRIMARY PrimaryCursor;
     2084    RTAsn1CursorInitPrimary(&PrimaryCursor,
     2085                            &pEntry->bCertificate[0],
     2086                            pEntry->dwLength - RT_OFFSETOF(WIN_CERTIFICATE, bCertificate),
     2087                            pErrInfo,
     2088                            &g_RTAsn1DefaultAllocator,
     2089                            0,
     2090                            "WinCert");
     2091
     2092    int rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &pSignature->ContentInfo, "CI");
     2093    if (RT_SUCCESS(rc))
     2094    {
     2095        if (RTCrPkcs7ContentInfo_IsSignedData(&pSignature->ContentInfo))
     2096        {
     2097            pSignature->pSignedData = pSignature->ContentInfo.u.pSignedData;
     2098
     2099            /*
     2100             * Decode the authenticode bits.
     2101             */
     2102            if (!strcmp(pSignature->pSignedData->ContentInfo.ContentType.szObjId, RTCRSPCINDIRECTDATACONTENT_OID))
     2103            {
     2104                pSignature->pIndData = pSignature->pSignedData->ContentInfo.u.pIndirectDataContent;
     2105                Assert(pSignature->pIndData);
     2106
     2107                /*
     2108                 * Check that things add up.
     2109                 */
     2110                if (RT_SUCCESS(rc))
     2111                    rc = RTCrPkcs7SignedData_CheckSanity(pSignature->pSignedData,
     2112                                                         RTCRPKCS7SIGNEDDATA_SANITY_F_AUTHENTICODE
     2113                                                         | RTCRPKCS7SIGNEDDATA_SANITY_F_ONLY_KNOWN_HASH
     2114                                                         | RTCRPKCS7SIGNEDDATA_SANITY_F_SIGNING_CERT_PRESENT,
     2115                                                         pErrInfo, "SD");
     2116                if (RT_SUCCESS(rc))
     2117                    rc = RTCrSpcIndirectDataContent_CheckSanityEx(pSignature->pIndData,
     2118                                                                  pSignature->pSignedData,
     2119                                                                  RTCRSPCINDIRECTDATACONTENT_SANITY_F_ONLY_KNOWN_HASH,
     2120                                                                  pErrInfo);
     2121                if (RT_SUCCESS(rc))
     2122                {
     2123                    PCRTCRX509ALGORITHMIDENTIFIER pDigestAlgorithm = &pSignature->pIndData->DigestInfo.DigestAlgorithm;
     2124                    pSignature->enmDigest = RTCrX509AlgorithmIdentifier_QueryDigestType(pDigestAlgorithm);
     2125                    AssertReturn(pSignature->enmDigest != RTDIGESTTYPE_INVALID, VERR_INTERNAL_ERROR_4); /* Checked above! */
     2126                }
     2127            }
     2128            else
     2129                rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_EXPECTED_INDIRECT_DATA_CONTENT_OID,
     2130                                   "Unknown pSignedData.ContentInfo.ContentType.szObjId value: %s (expected %s)",
     2131                                   pSignature->pSignedData->ContentInfo.ContentType.szObjId, RTCRSPCINDIRECTDATACONTENT_OID);
     2132        }
     2133    }
     2134    return rc;
     2135}
     2136
     2137
     2138static int rtldrPE_VerifyAllPageHashesV2(PRTLDRMODPE pModPe, PCRTCRSPCSERIALIZEDOBJECTATTRIBUTE pAttrib, RTDIGESTTYPE enmDigest,
     2139                                         void *pvScratch, size_t cbScratch, PRTERRINFO pErrInfo)
     2140{
     2141    AssertReturn(cbScratch >= _4K, VERR_INTERNAL_ERROR_3);
     2142
     2143    /*
     2144     * Calculate the special places.
     2145     */
     2146    RTLDRPEHASHSPECIALS SpecialPlaces;
     2147    int rc = rtldrPe_CalcSpecialHashPlaces(pModPe, &SpecialPlaces, pErrInfo);
     2148    if (RT_FAILURE(rc))
     2149        return rc;
     2150
     2151    uint32_t const cbHash = rtLdrPE_HashGetHashSize(enmDigest);
     2152    uint32_t const cPages = pAttrib->u.pPageHashesV2->RawData.Asn1Core.cb / (cbHash + 4);
     2153    if (cPages * (cbHash + 4) != pAttrib->u.pPageHashesV2->RawData.Asn1Core.cb)
     2154        return RTErrInfoSetF(pErrInfo, VERR_LDRVI_PAGE_HASH_TAB_SIZE_OVERFLOW,
     2155                             "Page Hashes V2 size issue: cb=%#x cbHash=%#x",
     2156                             pAttrib->u.pPageHashesV2->RawData.Asn1Core.cb, cbHash);
     2157
     2158    /*
     2159     * Walk the table.
     2160     */
     2161    uint32_t const  cbScratchReadMax = cbScratch & ~(uint32_t)(_4K - 1);
     2162    uint32_t        cbScratchRead    = 0;
     2163    uint32_t        offScratchRead   = 0;
     2164
     2165    uint32_t        offPrev    = 0;
     2166    uint32_t        offSectEnd = pModPe->cbHeaders;
     2167    uint32_t        iSh        = UINT32_MAX;
     2168    uint8_t const  *pbHashTab  = pAttrib->u.pPageHashesV2->RawData.Asn1Core.uData.pu8;
     2169    for (uint32_t iPage = 0; iPage < cPages; iPage++)
     2170    {
     2171        /* Decode the page offset. */
     2172        uint32_t const offFile = RT_MAKE_U32_FROM_U8(pbHashTab[0], pbHashTab[1], pbHashTab[2], pbHashTab[3]);
     2173        if (offFile >= SpecialPlaces.cbToHash)
     2174        {
     2175            /* The last entry is zero. */
     2176            if (   offFile   == SpecialPlaces.cbToHash
     2177                && iPage + 1 == cPages
     2178                && ASMMemIsAll8(pbHashTab + 4, cbHash, 0) == NULL)
     2179                return VINF_SUCCESS;
     2180            return RTErrInfoSetF(pErrInfo, VERR_LDRVI_PAGE_HASH_TAB_TOO_LONG,
     2181                                 "Page hash entry #%u is beyond the signature table start: %#x, %#x",
     2182                                 iPage, offFile, SpecialPlaces.cbToHash);
     2183        }
     2184        if (offFile < offPrev)
     2185            return RTErrInfoSetF(pErrInfo, VERR_LDRVI_PAGE_HASH_TAB_NOT_STRICTLY_SORTED,
     2186                                 "Page hash table is not strictly sorted: entry #%u @%#x, previous @%#x\n",
     2187                                 iPage, offFile, offPrev);
     2188
     2189        /* Figure out how much to read and how much to zero.  Need keep track
     2190           of the on-disk section boundraries. */
     2191        if (offFile >= offSectEnd)
     2192        {
     2193            iSh++;
     2194            if (   iSh < pModPe->cSections
     2195                && offFile - pModPe->paSections[iSh].PointerToRawData < pModPe->paSections[iSh].SizeOfRawData)
     2196                offSectEnd = pModPe->paSections[iSh].PointerToRawData + pModPe->paSections[iSh].SizeOfRawData;
     2197            else
     2198            {
     2199                iSh = 0;
     2200                while (   iSh < pModPe->cSections
     2201                       && offFile - pModPe->paSections[iSh].PointerToRawData >= pModPe->paSections[iSh].SizeOfRawData)
     2202                    iSh++;
     2203                if (iSh < pModPe->cSections)
     2204                    offSectEnd = pModPe->paSections[iSh].PointerToRawData + pModPe->paSections[iSh].SizeOfRawData;
     2205                else
     2206                    return RTErrInfoSetF(pErrInfo, VERR_PAGE_HASH_TAB_HASHES_NON_SECTION_DATA,
     2207                                         "Page hash entry #%u isn't in any section: %#x", iPage, offFile);
     2208            }
     2209        }
     2210
     2211        uint32_t cbRead = _4K;
     2212        if (offFile + cbRead > offSectEnd)
     2213            cbRead = offSectEnd - offFile;
     2214
     2215        if (offFile + cbRead > SpecialPlaces.cbToHash)
     2216            cbRead = SpecialPlaces.cbToHash - offFile;
     2217
     2218        /* Did we get a cache hit? */
     2219        uint8_t *pbCur = (uint8_t *)pvScratch;
     2220        if (   offFile + cbRead <= offScratchRead + cbScratchRead
     2221            && offFile          >= offScratchRead)
     2222            pbCur += offFile - offScratchRead;
     2223        /* Missed, read more. */
     2224        else
     2225        {
     2226            offScratchRead = offFile;
     2227            cbScratchRead  = offSectEnd - offFile;
     2228            if (cbScratchRead > cbScratchReadMax)
     2229                cbScratchRead = cbScratchReadMax;
     2230            rc = pModPe->Core.pReader->pfnRead(pModPe->Core.pReader, pbCur, cbScratchRead, offScratchRead);
     2231            if (RT_FAILURE(rc))
     2232                return RTErrInfoSetF(pErrInfo, VERR_LDRVI_READ_ERROR_HASH,
     2233                                     "Page hash read error at %#x: %Rrc (cbScratchRead=%#zx)",
     2234                                     offScratchRead, rc, cbScratchRead);
     2235        }
     2236
     2237        /* Zero any additional bytes in the page. */
     2238        if (cbRead != _4K)
     2239            memset(pbCur + cbRead, 0, _4K - cbRead);
     2240
     2241        /*
     2242         * Hash it.
     2243         */
     2244        RTLDRPEHASHCTXUNION HashCtx;
     2245        rc = rtLdrPE_HashInit(&HashCtx, enmDigest);
     2246        AssertRCReturn(rc, rc);
     2247
     2248        /* Deal with special places. */
     2249        uint32_t       cbLeft = _4K;
     2250        if (offFile < SpecialPlaces.offEndSpecial)
     2251        {
     2252            uint32_t off = offFile;
     2253            if (off < SpecialPlaces.offCksum)
     2254            {
     2255                /* Hash everything up to the checksum. */
     2256                uint32_t cbChunk = RT_MIN(SpecialPlaces.offCksum - off, cbLeft);
     2257                rtLdrPE_HashUpdate(&HashCtx, enmDigest, pbCur, cbChunk);
     2258                pbCur  += cbChunk;
     2259                cbLeft -= cbChunk;
     2260                off    += cbChunk;
     2261            }
     2262
     2263            if (off < SpecialPlaces.offCksum + SpecialPlaces.cbCksum && off >= SpecialPlaces.offCksum)
     2264            {
     2265                /* Skip the checksum */
     2266                uint32_t cbChunk = RT_MIN(SpecialPlaces.offCksum + SpecialPlaces.cbCksum - off, cbLeft);
     2267                pbCur  += cbChunk;
     2268                cbLeft -= cbChunk;
     2269                off    += cbChunk;
     2270            }
     2271
     2272            if (off < SpecialPlaces.offSecDir && off >= SpecialPlaces.offCksum + SpecialPlaces.cbCksum)
     2273            {
     2274                /* Hash everything between the checksum and the data dir entry. */
     2275                uint32_t cbChunk = RT_MIN(SpecialPlaces.offSecDir - off, cbLeft);
     2276                rtLdrPE_HashUpdate(&HashCtx, enmDigest, pbCur, cbChunk);
     2277                pbCur  += cbChunk;
     2278                cbLeft -= cbChunk;
     2279                off    += cbChunk;
     2280            }
     2281
     2282            if (off < SpecialPlaces.offSecDir + SpecialPlaces.cbSecDir && off >= SpecialPlaces.offSecDir)
     2283            {
     2284                /* Skip the security data directory entry. */
     2285                uint32_t cbChunk = RT_MIN(SpecialPlaces.offSecDir + SpecialPlaces.cbSecDir - off, cbLeft);
     2286                pbCur  += cbChunk;
     2287                cbLeft -= cbChunk;
     2288                off    += cbChunk;
     2289            }
     2290        }
     2291
     2292        rtLdrPE_HashUpdate(&HashCtx, enmDigest, pbCur, cbLeft);
     2293
     2294        /*
     2295         * Finish the hash calculation and compare the result.
     2296         */
     2297        RTLDRPEHASHRESUNION HashRes;
     2298        rtLdrPE_HashFinalize(&HashCtx, enmDigest, &HashRes);
     2299
     2300        pbHashTab += 4;
     2301        if (memcmp(pbHashTab, &HashRes, cbHash) != 0)
     2302            return RTErrInfoSetF(pErrInfo, VERR_LDRVI_PAGE_HASH_MISMATCH,
     2303                                 "Page hash v2 failed for page #%u, @%#x, %#x bytes: %.*Rhxs != %.*Rhxs",
     2304                                 iPage, offFile, cbRead, (size_t)cbHash, pbHashTab, (size_t)cbHash, &HashRes);
     2305        pbHashTab += cbHash;
     2306        offPrev = offFile;
     2307    }
     2308
     2309    return VINF_SUCCESS;
     2310}
     2311
     2312
     2313/**
     2314 * Validates the image hash, including page hashes if present.
     2315 *
     2316 * @returns IPRT status code.
     2317 * @param   pModPe              The PE module.
     2318 * @param   pSignature          The decoded signature data.
     2319 * @param   pErrInfo            Optional error info buffer.
     2320 */
     2321static int rtldrPE_VerifySignatureValidateHash(PRTLDRMODPE pModPe, PRTLDRPESIGNATURE pSignature, PRTERRINFO pErrInfo)
     2322{
     2323    AssertReturn(pSignature->enmDigest > RTDIGESTTYPE_INVALID && pSignature->enmDigest < RTDIGESTTYPE_END, VERR_INTERNAL_ERROR_4);
     2324    AssertPtrReturn(pSignature->pIndData, VERR_INTERNAL_ERROR_5);
     2325    AssertReturn(RTASN1CORE_IS_PRESENT(&pSignature->pIndData->DigestInfo.Digest.Asn1Core), VERR_INTERNAL_ERROR_5);
     2326    AssertPtrReturn(pSignature->pIndData->DigestInfo.Digest.Asn1Core.uData.pv, VERR_INTERNAL_ERROR_5);
     2327
     2328    uint32_t const cbHash = rtLdrPE_HashGetHashSize(pSignature->enmDigest);
     2329    AssertReturn(pSignature->pIndData->DigestInfo.Digest.Asn1Core.cb == cbHash, VERR_INTERNAL_ERROR_5);
     2330
     2331    /*
     2332     * Allocate a temporary memory buffer.
     2333     */
     2334#ifdef IN_RING0
     2335    uint32_t    cbScratch = _256K;
     2336#else
     2337    uint32_t    cbScratch = _1M;
     2338#endif
     2339    void       *pvScratch = RTMemTmpAlloc(cbScratch);
     2340    if (!pvScratch)
     2341    {
     2342        cbScratch = _4K;
     2343        pvScratch = RTMemTmpAlloc(cbScratch);
     2344        if (!pvScratch)
     2345            return RTErrInfoSet(pErrInfo, VERR_NO_TMP_MEMORY, "Failed to allocate 4KB of scratch space for hashing image.");
     2346    }
     2347
     2348    /*
     2349     * Calculate and compare the full image hash.
     2350     */
     2351    int rc = rtldrPE_HashImageCommon(pModPe, pvScratch, cbScratch, pSignature->enmDigest,
     2352                                     &pSignature->HashCtx, &pSignature->HashRes, pErrInfo);
     2353    if (RT_SUCCESS(rc))
     2354    {
     2355        if (!memcmp(&pSignature->HashRes, pSignature->pIndData->DigestInfo.Digest.Asn1Core.uData.pv, cbHash))
     2356        {
     2357            /*
     2358             * Compare the page hashes if present.
     2359             */
     2360            PCRTCRSPCSERIALIZEDOBJECTATTRIBUTE pAttrib = RTCrSpcIndirectDataContent_GetPeImageHashesV2(pSignature->pIndData);
     2361            if (pAttrib)
     2362                rc = rtldrPE_VerifyAllPageHashesV2(pModPe, pAttrib, pSignature->enmDigest, pvScratch, cbScratch, pErrInfo);
     2363
     2364            return rc;
     2365        }
     2366        rc = RTErrInfoSetF(pErrInfo, VERR_LDRVI_IMAGE_HASH_MISMATCH,
     2367                           "Full image signature mismatch: %.*Rhxs, expected %.*Rhxs",
     2368                           cbHash, &pSignature->HashRes,
     2369                           cbHash, pSignature->pIndData->DigestInfo.Digest.Asn1Core.uData.pv);
     2370    }
     2371
     2372    RTMemTmpFree(pvScratch);
     2373    return rc;
     2374}
     2375
     2376#endif /* !IPRT_WITHOUT_LDR_VERIFY */
     2377
     2378
     2379/** @interface_method_impl{RTLDROPS,pfnVerifySignature} */
     2380static DECLCALLBACK(int) rtldrPE_VerifySignature(PRTLDRMODINTERNAL pMod, PFNRTLDRVALIDATESIGNEDDATA pfnCallback, void *pvUser,
     2381                                                 PRTERRINFO pErrInfo)
     2382{
     2383#ifndef IPRT_WITHOUT_LDR_VERIFY
     2384    PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
     2385
     2386    int rc = rtldrPE_VerifySignatureImagePrecoditions(pModPe, pErrInfo);
     2387    if (RT_SUCCESS(rc))
     2388    {
     2389        PRTLDRPESIGNATURE pSignature = NULL;
     2390        rc = rtldrPE_VerifySignatureRead(pModPe, &pSignature, pErrInfo);
     2391        if (RT_SUCCESS(rc))
     2392        {
     2393            rc = rtldrPE_VerifySignatureDecode(pModPe, pSignature, pErrInfo);
     2394            if (RT_SUCCESS(rc))
     2395                rc = rtldrPE_VerifySignatureValidateHash(pModPe, pSignature, pErrInfo);
     2396            if (RT_SUCCESS(rc))
     2397            {
     2398                rc = pfnCallback(&pModPe->Core, RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA,
     2399                                 &pSignature->ContentInfo, sizeof(pSignature->ContentInfo),
     2400                                 pErrInfo, pvUser);
     2401            }
     2402            rtldrPE_VerifySignatureDestroy(pModPe, pSignature);
     2403        }
     2404    }
     2405    return rc;
     2406#else
     2407    return VERR_NOT_SUPPORTED;
     2408#endif
     2409}
     2410
     2411
     2412
     2413/**  @interface_method_impl{RTLDROPS,pfnHashImage}  */
     2414static DECLCALLBACK(int) rtldrPE_HashImage(PRTLDRMODINTERNAL pMod, RTDIGESTTYPE enmDigest, char *pszDigest, size_t cbDigest)
     2415{
     2416    PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
     2417
     2418    /*
     2419     * Allocate a temporary memory buffer.
     2420     */
     2421    uint32_t    cbScratch = _16K;
     2422    void       *pvScratch = RTMemTmpAlloc(cbScratch);
     2423    if (!pvScratch)
     2424    {
     2425        cbScratch = _4K;
     2426        pvScratch = RTMemTmpAlloc(cbScratch);
     2427        if (!pvScratch)
     2428            return VERR_NO_TMP_MEMORY;
     2429    }
     2430
     2431    /*
     2432     * Do the hashing.
     2433     */
     2434    RTLDRPEHASHCTXUNION HashCtx;
     2435    RTLDRPEHASHRESUNION HashRes;
     2436    int rc = rtldrPE_HashImageCommon(pModPe, pvScratch, cbScratch, enmDigest, &HashCtx, &HashRes, NULL);
     2437    if (RT_SUCCESS(rc))
     2438    {
     2439        /*
     2440         * Format the digest into as human readable hash string.
     2441         */
     2442        switch (enmDigest)
     2443        {
     2444            case RTDIGESTTYPE_SHA512:  rc = RTSha512ToString(HashRes.abSha512, pszDigest, cbDigest); break;
     2445            case RTDIGESTTYPE_SHA256:  rc = RTSha256ToString(HashRes.abSha256, pszDigest, cbDigest); break;
     2446            case RTDIGESTTYPE_SHA1:    rc = RTSha1ToString(HashRes.abSha1, pszDigest, cbDigest); break;
     2447            case RTDIGESTTYPE_MD5:     rc = RTMd5ToString(HashRes.abMd5, pszDigest, cbDigest); break;
     2448            default:                   AssertFailedReturn(VERR_INTERNAL_ERROR_3);
     2449        }
     2450    }
     2451    return rc;
     2452}
     2453
     2454
    15142455/** @copydoc RTLDROPS::pfnDone */
    15152456static DECLCALLBACK(int) rtldrPEDone(PRTLDRMODINTERNAL pMod)
     
    15232464    return VINF_SUCCESS;
    15242465}
     2466
    15252467
    15262468/** @copydoc RTLDROPS::pfnClose */
     
    15662508        NULL,
    15672509        rtldrPE_QueryProp,
     2510        rtldrPE_VerifySignature,
     2511        rtldrPE_HashImage,
    15682512        42
    15692513    },
     
    15972541        NULL,
    15982542        rtldrPE_QueryProp,
     2543        rtldrPE_VerifySignature,
     2544        rtldrPE_HashImage,
    15992545        42
    16002546    },
     
    16602606     * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
    16612607     */
    1662     IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
    1663     IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
    1664 
    1665     pLoadCfg64->SEHandlerCount             = pLoadCfg32->SEHandlerCount;
    1666     pLoadCfg64->SEHandlerTable             = pLoadCfg32->SEHandlerTable;
    1667     pLoadCfg64->SecurityCookie             = pLoadCfg32->SecurityCookie;
    1668     pLoadCfg64->EditList                   = pLoadCfg32->EditList;
    1669     pLoadCfg64->Reserved1                  = pLoadCfg32->Reserved1;
    1670     pLoadCfg64->CSDVersion                 = pLoadCfg32->CSDVersion;
    1671     pLoadCfg64->ProcessHeapFlags           = pLoadCfg32->ProcessHeapFlags; /* switched place with ProcessAffinityMask, but we're more than 16 byte off by now so it doesn't matter. */
    1672     pLoadCfg64->ProcessAffinityMask        = pLoadCfg32->ProcessAffinityMask;
    1673     pLoadCfg64->VirtualMemoryThreshold     = pLoadCfg32->VirtualMemoryThreshold;
    1674     pLoadCfg64->MaximumAllocationSize      = pLoadCfg32->MaximumAllocationSize;
    1675     pLoadCfg64->LockPrefixTable            = pLoadCfg32->LockPrefixTable;
    1676     pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
    1677     uint32_t u32DeCommitFreeBlockThreshold = pLoadCfg32->DeCommitFreeBlockThreshold;
    1678     pLoadCfg64->DeCommitFreeBlockThreshold = u32DeCommitFreeBlockThreshold;
     2608    IMAGE_LOAD_CONFIG_DIRECTORY32_V3 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32_V3 volatile *)pLoadCfg;
     2609    IMAGE_LOAD_CONFIG_DIRECTORY64_V3 volatile *pLoadCfg64 = pLoadCfg;
     2610
     2611    pLoadCfg64->GuardFlags                  = pLoadCfg32->GuardFlags;
     2612    pLoadCfg64->GuardCFFunctionCount        = pLoadCfg32->GuardCFFunctionCount;
     2613    pLoadCfg64->GuardCFFunctionTable        = pLoadCfg32->GuardCFFunctionTable;
     2614    pLoadCfg64->Reserved2                   = pLoadCfg32->Reserved2;
     2615    pLoadCfg64->GuardCFCCheckFunctionPointer= pLoadCfg32->GuardCFCCheckFunctionPointer;
     2616    pLoadCfg64->SEHandlerCount              = pLoadCfg32->SEHandlerCount;
     2617    pLoadCfg64->SEHandlerTable              = pLoadCfg32->SEHandlerTable;
     2618    pLoadCfg64->SecurityCookie              = pLoadCfg32->SecurityCookie;
     2619    pLoadCfg64->EditList                    = pLoadCfg32->EditList;
     2620    pLoadCfg64->Reserved1                   = pLoadCfg32->Reserved1;
     2621    pLoadCfg64->CSDVersion                  = pLoadCfg32->CSDVersion;
     2622    pLoadCfg64->ProcessHeapFlags            = pLoadCfg32->ProcessHeapFlags; /* switched place with ProcessAffinityMask, but we're more than 16 byte off by now so it doesn't matter. */
     2623    pLoadCfg64->ProcessAffinityMask         = pLoadCfg32->ProcessAffinityMask;
     2624    pLoadCfg64->VirtualMemoryThreshold      = pLoadCfg32->VirtualMemoryThreshold;
     2625    pLoadCfg64->MaximumAllocationSize       = pLoadCfg32->MaximumAllocationSize;
     2626    pLoadCfg64->LockPrefixTable             = pLoadCfg32->LockPrefixTable;
     2627    pLoadCfg64->DeCommitTotalFreeThreshold  = pLoadCfg32->DeCommitTotalFreeThreshold;
     2628    uint32_t u32DeCommitFreeBlockThreshold  = pLoadCfg32->DeCommitFreeBlockThreshold;
     2629    pLoadCfg64->DeCommitFreeBlockThreshold  = u32DeCommitFreeBlockThreshold;
    16792630    /* the rest is equal. */
    16802631    Assert(     RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, DeCommitFreeBlockThreshold)
     
    17202671    /* This restriction needs to be implemented elsewhere. */
    17212672    if (   (pFileHdr->Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
    1722         && !(fFlags & RTLDR_O_FOR_DEBUG))
     2673        && !(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
    17232674    {
    17242675        Log(("rtldrPEOpen: %s: IMAGE_FILE_RELOCS_STRIPPED\n", pszLogName));
     
    18562807
    18572808            case IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT:  // 13
     2809                if (fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION))
     2810                    break;
    18582811                Log(("rtldrPEOpen: %s: dir no. %d (DELAY_IMPORT) VirtualAddress=%#x Size=%#x is not supported!!!\n",
    18592812                     pszLogName, i, pDir->VirtualAddress, pDir->Size));
     
    18702823                    return VERR_LDRPE_CERT_MALFORMED;
    18712824                }
    1872                 if (pDir->Size >= _1M)
     2825                if (pDir->Size >= RTLDRMODPE_MAX_SECURITY_DIR_SIZE)
    18732826                {
    18742827                    Log(("rtldrPEOpen: %s: Security directory is too large: %#x bytes\n", pszLogName, i, pDir->Size));
     
    18942847
    18952848            case IMAGE_DIRECTORY_ENTRY_TLS:           // 9
     2849                if (fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION))
     2850                    break;
    18962851                Log(("rtldrPEOpen: %s: dir no. %d (TLS) VirtualAddress=%#x Size=%#x is not supported!!!\n",
    18972852                     pszLogName, i, pDir->VirtualAddress, pDir->Size));
     
    18992854
    19002855            case IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR:// 14
     2856                if (fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION))
     2857                    break;
    19012858                Log(("rtldrPEOpen: %s: dir no. %d (COM_DESCRIPTOR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
    19022859                     pszLogName, i, pDir->VirtualAddress, pDir->Size));
     
    19452902    for (unsigned cSHdrsLeft = cSections;  cSHdrsLeft > 0; cSHdrsLeft--, pSH++)
    19462903    {
    1947         const unsigned iSH = pSH - &paSections[0]; NOREF(iSH);
     2904        const unsigned iSH = (unsigned)(pSH - &paSections[0]); NOREF(iSH);
    19482905        Log3(("RTLdrPE: #%d '%-8.8s'  Characteristics: %08RX32\n"
    19492906              "RTLdrPE: VirtAddr: %08RX32  VirtSize: %08RX32\n"
     
    21103067
    21113068/**
    2112  * Validates the data of some selected data directories entries.
    2113  *
    2114  * This requires a valid section table and thus has to wait
    2115  * till after we've read and validated it.
     3069 * Validates the data of some selected data directories entries and remember
     3070 * important bits for later.
     3071 *
     3072 * This requires a valid section table and thus has to wait till after we've
     3073 * read and validated it.
    21163074 *
    21173075 * @returns iprt status code.
     
    21203078 * @param   fFlags      Loader flags, RTLDR_O_XXX.
    21213079 */
    2122 static int rtldrPEValidateDirectories(PRTLDRMODPE pModPe, const IMAGE_OPTIONAL_HEADER64 *pOptHdr, uint32_t fFlags)
     3080static int rtldrPEValidateDirectoriesAndRememberStuff(PRTLDRMODPE pModPe, const IMAGE_OPTIONAL_HEADER64 *pOptHdr, uint32_t fFlags)
    21233081{
    21243082    const char *pszLogName = pModPe->Core.pReader->pfnLogName(pModPe->Core.pReader); NOREF(pszLogName);
     
    21363094    if (Dir.Size)
    21373095    {
    2138         const size_t cbExpect = pOptHdr->Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC
    2139             ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
    2140             : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64);
    2141         if (    Dir.Size != cbExpect
    2142             && (    cbExpect == sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
    2143                 &&  Dir.Size != (uint32_t)RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, SEHandlerTable))
    2144            )
    2145         {
    2146             Log(("rtldrPEOpen: %s: load cfg dir: unexpected dir size of %d bytes, expected %d.\n",
    2147                  pszLogName, Dir.Size, cbExpect));
     3096        const size_t cbExpectV3 = !pModPe->f64Bit
     3097                                ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32_V3)
     3098                                : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64_V3);
     3099        const size_t cbExpectV2 = !pModPe->f64Bit
     3100                                ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32_V2)
     3101                                : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64_V2);
     3102        const size_t cbExpectV1 = !pModPe->f64Bit
     3103                                ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32_V1)
     3104                                : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64_V2) /*No V1*/;
     3105
     3106        if (   Dir.Size != cbExpectV3
     3107            && Dir.Size != cbExpectV2
     3108            && Dir.Size != cbExpectV1)
     3109        {
     3110            Log(("rtldrPEOpen: %s: load cfg dir: unexpected dir size of %d bytes, expected %d, %d, or %d.\n",
     3111                 pszLogName, Dir.Size, cbExpectV3, cbExpectV2, cbExpectV1));
    21483112            return VERR_LDRPE_LOAD_CONFIG_SIZE;
    21493113        }
     
    21583122        rtldrPEConvert32BitLoadConfigTo64Bit(&u.Cfg64);
    21593123
    2160         if (u.Cfg64.Size != cbExpect)
    2161         {
    2162             Log(("rtldrPEOpen: %s: load cfg dir: unexpected header size of %d bytes, expected %d.\n",
    2163                  pszLogName, u.Cfg64.Size, cbExpect));
    2164             return VERR_LDRPE_LOAD_CONFIG_SIZE;
    2165         }
    2166         if (u.Cfg64.LockPrefixTable)
     3124        if (u.Cfg64.Size != Dir.Size)
     3125        {
     3126            /* Kludge, seen ati shipping 32-bit DLLs and EXEs with Dir.Size=0x40
     3127               and Cfg64.Size=0x5c or 0x48.  Windows seems to deal with it, so
     3128               lets do so as well. */
     3129            if (   Dir.Size < u.Cfg64.Size
     3130                && (   u.Cfg64.Size == cbExpectV3
     3131                    || u.Cfg64.Size == cbExpectV2) )
     3132            {
     3133                Log(("rtldrPEOpen: %s: load cfg dir: Header (%d) and directory (%d) size mismatch, applying the ATI kludge\n",
     3134                     pszLogName, u.Cfg64.Size, Dir.Size));
     3135                Dir.Size = u.Cfg64.Size;
     3136                memset(&u.Cfg64, 0, sizeof(u.Cfg64));
     3137                rc = rtldrPEReadRVA(pModPe, &u.Cfg64, Dir.Size, Dir.VirtualAddress);
     3138                if (RT_FAILURE(rc))
     3139                    return rc;
     3140                rtldrPEConvert32BitLoadConfigTo64Bit(&u.Cfg64);
     3141            }
     3142            if (u.Cfg64.Size != Dir.Size)
     3143            {
     3144                Log(("rtldrPEOpen: %s: load cfg dir: unexpected header size of %d bytes, expected %d.\n",
     3145                     pszLogName, u.Cfg64.Size, Dir.Size));
     3146                return VERR_LDRPE_LOAD_CONFIG_SIZE;
     3147            }
     3148        }
     3149        if (u.Cfg64.LockPrefixTable && !(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
    21673150        {
    21683151            Log(("rtldrPEOpen: %s: load cfg dir: lock prefix table at %RX64. We don't support lock prefix tables!\n",
     
    21793162        }
    21803163#endif
    2181         if (u.Cfg64.EditList)
     3164        if (u.Cfg64.EditList && !(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
    21823165        {
    21833166            Log(("rtldrPEOpen: %s: load cfg dir: EditList=%RX64 is unsupported!\n",
     
    21853168            return VERR_BAD_EXE_FORMAT;
    21863169        }
     3170        /** @todo GuardCFC? Possibly related to:
     3171         *         http://research.microsoft.com/pubs/69217/ccs05-cfi.pdf
     3172         * Not trusting something designed by bakas who don't know how to modify a
     3173         * structure without messing up its natural alignment. */
     3174        if (    (   u.Cfg64.GuardCFCCheckFunctionPointer
     3175                 || u.Cfg64.Reserved2
     3176                 || u.Cfg64.GuardCFFunctionTable
     3177                 || u.Cfg64.GuardCFFunctionCount
     3178                 || u.Cfg64.GuardFlags)
     3179            && !(fFlags & (RTLDR_O_FOR_DEBUG | RTLDR_O_FOR_VALIDATION)))
     3180        {
     3181            Log(("rtldrPEOpen: %s: load cfg dir: Guard stuff: %RX64,%RX64,%RX64,%RX64,%RX32!\n",
     3182                 pszLogName, u.Cfg64.GuardCFCCheckFunctionPointer, u.Cfg64.Reserved2,
     3183                 u.Cfg64.GuardCFFunctionTable, u.Cfg64.GuardCFFunctionCount, u.Cfg64.GuardFlags));
     3184            return VERR_BAD_EXE_FORMAT;
     3185        }
    21873186    }
    21883187
     
    21923191     */
    21933192    Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
    2194     if (Dir.Size && !(fFlags & RTLDR_O_FOR_DEBUG))
     3193    if (Dir.Size)
    21953194    {
    21963195        PWIN_CERTIFICATE pFirst = (PWIN_CERTIFICATE)RTMemTmpAlloc(Dir.Size);
     
    22003199        if (RT_SUCCESS(rc))
    22013200        {
    2202             uint32_t         off  = 0;
    2203             PWIN_CERTIFICATE pCur = pFirst;
     3201            uint32_t off  = 0;
    22043202            do
    22053203            {
     3204                PWIN_CERTIFICATE pCur = (PWIN_CERTIFICATE)((uint8_t *)pFirst + off);
     3205
    22063206                /* validate the members. */
    2207                 uint32_t const cbCur = RT_ALIGN_32(pCur->dwLength, 8);
    2208                 if (   cbCur < sizeof(WIN_CERTIFICATE)
    2209                     || cbCur + off > RT_ALIGN_32(Dir.Size, 8))
     3207                if (   pCur->dwLength < sizeof(WIN_CERTIFICATE)
     3208                    || pCur->dwLength + off > Dir.Size)
    22103209                {
    22113210                    Log(("rtldrPEOpen: %s: cert at %#x/%#x: dwLength=%#x\n", pszLogName, off, Dir.Size, pCur->dwLength));
     
    22333232                }
    22343233
    2235                 /** @todo Rainy Day: Implement further verification using openssl. */
     3234                /* Remember the first signed data certificate. */
     3235                if (   pCur->wCertificateType == WIN_CERT_TYPE_PKCS_SIGNED_DATA
     3236                    && pModPe->offPkcs7SignedData == 0)
     3237                {
     3238                    pModPe->offPkcs7SignedData = Dir.VirtualAddress
     3239                                               + (uint32_t)((uintptr_t)&pCur->bCertificate[0] - (uintptr_t)pFirst);
     3240                    pModPe->cbPkcs7SignedData  = pCur->dwLength - RT_OFFSETOF(WIN_CERTIFICATE, bCertificate);
     3241                }
    22363242
    22373243                /* next */
    2238                 off += cbCur;
    2239                 pCur = (PWIN_CERTIFICATE)((uint8_t *)pCur + cbCur);
     3244                off += RT_ALIGN(pCur->dwLength, WIN_CERTIFICATE_ALIGNMENT);
    22403245            } while (off < Dir.Size);
    22413246        }
     
    22593264 * @param   offNtHdrs   The offset of the NT headers (where you find "PE\0\0").
    22603265 * @param   phLdrMod    Where to store the handle.
    2261  */
    2262 int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs, PRTLDRMOD phLdrMod)
     3266 * @param   pErrInfo    Where to return extended error information. Optional.
     3267 */
     3268int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs,
     3269                PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
    22633270{
    22643271    /*
     
    23493356                pModPe->cbHeaders     = OptHdr.SizeOfHeaders;
    23503357                pModPe->uTimestamp    = FileHdr.TimeDateStamp;
     3358                pModPe->f64Bit        = FileHdr.SizeOfOptionalHeader == sizeof(OptHdr);
    23513359                pModPe->ImportDir     = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
    23523360                pModPe->RelocDir      = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
    23533361                pModPe->ExportDir     = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
    23543362                pModPe->DebugDir      = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
     3363                pModPe->SecurityDir   = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
     3364                pModPe->fDllCharacteristics = OptHdr.DllCharacteristics;
    23553365
    23563366                /*
    23573367                 * Perform validation of some selected data directories which requires
    2358                  * inspection of the actual data.
     3368                 * inspection of the actual data.  This also saves some certificate
     3369                 * information.
    23593370                 */
    2360                 rc = rtldrPEValidateDirectories(pModPe, &OptHdr, fFlags);
     3371                rc = rtldrPEValidateDirectoriesAndRememberStuff(pModPe, &OptHdr, fFlags);
    23613372                if (RT_SUCCESS(rc))
    23623373                {
  • trunk/src/VBox/Runtime/common/ldr/ldrkStuff.cpp

    r49045 r51770  
    838838
    839839/** @interface_method_impl{RTLDROPS,pfnQueryProp} */
    840 static DECLCALLBACK(int) rtkldr_QueryProp(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf)
     840static DECLCALLBACK(int) rtkldr_QueryProp(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf, size_t *pcbRet)
    841841{
    842842    PRTLDRMODKLDR pThis = (PRTLDRMODKLDR)pMod;
     
    881881    rtkldr_ReadDbgInfo,
    882882    rtkldr_QueryProp,
     883    NULL,
     884    NULL,
    883885    42
    884886};
     
    893895 * @param   enmArch     CPU architecture specifier for the image to be loaded.
    894896 * @param   phLdrMod    Where to store the handle.
     897 * @param   pErrInfo    Where to return extended error information. Optional.
    895898 */
    896 int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod)
     899int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo)
    897900{
    898901    /* Convert enmArch to k-speak. */
  • trunk/src/VBox/Runtime/common/log/log.cpp

    r50915 r51770  
    26092609RT_EXPORT_SYMBOL(RTLogPrintfV);
    26102610
     2611
     2612/**
     2613 * Dumper vprintf-like function outputting to a logger.
     2614 *
     2615 * @param   pvUser          Pointer to the logger instance to use, NULL for
     2616 *                          default instance.
     2617 * @param   pszFormat       Format string.
     2618 * @param   va              Format arguments.
     2619 */
     2620RTDECL(void) RTLogDumpPrintfV(void *pvUser, const char *pszFormat, va_list va)
     2621{
     2622    RTLogLoggerV((PRTLOGGER)pvUser, pszFormat, va);
     2623}
     2624RT_EXPORT_SYMBOL(RTLogDumpPrintfV);
     2625
     2626
    26112627#ifdef IN_RING3
    26122628
  • trunk/src/VBox/Runtime/common/misc/sg.cpp

    r44529 r51770  
    4848    }
    4949
     50#ifndef RDESKTOP
    5051    AssertReleaseMsg(      pSgBuf->cbSegLeft <= 32 * _1M
    5152                     &&    (uintptr_t)pSgBuf->pvSegCur                     >= (uintptr_t)pSgBuf->paSegs[pSgBuf->idxSeg].pvSeg
     
    5455                      pSgBuf->idxSeg, pSgBuf->cSegs, pSgBuf->pvSegCur, pSgBuf->cbSegLeft,
    5556                      pSgBuf->idxSeg, pSgBuf->paSegs[pSgBuf->idxSeg].pvSeg, pSgBuf->idxSeg, pSgBuf->paSegs[pSgBuf->idxSeg].cbSeg));
     57#endif
    5658
    5759    cbData = RT_MIN(*pcbData, pSgBuf->cbSegLeft);
  • trunk/src/VBox/Runtime/common/string/RTStrPrintHexBytes.cpp

    r44529 r51770  
    55
    66/*
    7  * Copyright (C) 2009-2010 Oracle Corporation
     7 * Copyright (C) 2009-2014 Oracle Corporation
    88 *
    99 * This file is part of VirtualBox Open Source Edition (OSE), as
     
    3838RTDECL(int) RTStrPrintHexBytes(char *pszBuf, size_t cchBuf, void const *pv, size_t cb, uint32_t fFlags)
    3939{
    40     AssertReturn(!fFlags, VERR_INVALID_PARAMETER);
     40    AssertReturn(!(fFlags & ~RTSTRPRINTHEXBYTES_F_UPPER), VERR_INVALID_PARAMETER);
    4141    AssertPtrReturn(pszBuf, VERR_INVALID_POINTER);
    4242    AssertReturn(cb * 2 >= cb, VERR_BUFFER_OVERFLOW);
     
    4545        AssertPtrReturn(pv, VERR_INVALID_POINTER);
    4646
     47    static char const s_szHexDigitsLower[17] = "0123456789abcdef";
     48    static char const s_szHexDigitsUpper[17] = "0123456789ABCDEF";
     49    const char *pszHexDigits = !(fFlags & RTSTRPRINTHEXBYTES_F_UPPER) ? s_szHexDigitsLower : s_szHexDigitsUpper;
     50
    4751    uint8_t const *pb = (uint8_t const *)pv;
    4852    while (cb-- > 0)
    4953    {
    50         static char const s_szHexDigits[17] = "0123456789abcdef";
    5154        uint8_t b = *pb++;
    52         *pszBuf++ = s_szHexDigits[b >> 4];
    53         *pszBuf++ = s_szHexDigits[b & 0xf];
     55        *pszBuf++ = pszHexDigits[b >> 4];
     56        *pszBuf++ = pszHexDigits[b & 0xf];
    5457    }
    5558    *pszBuf = '\0';
  • trunk/src/VBox/Runtime/common/string/base64.cpp

    r44529 r51770  
    3535#include <iprt/err.h>
    3636#include <iprt/ctype.h>
     37#include <iprt/string.h>
    3738#ifdef RT_STRICT
    3839# include <iprt/asm.h>
     
    120121
    121122
    122 /**
    123  * Calculates the decoded data size for a Base64 encoded string.
    124  *
    125  * @returns The length in bytes. -1 if the encoding is bad.
    126  *
    127  * @param   pszString           The Base64 encoded string.
    128  * @param   ppszEnd             If not NULL, this will point to the first char
    129  *                              following the Base64 encoded text block. If
    130  *                              NULL the entire string is assumed to be Base64.
    131  */
    132 RTDECL(ssize_t) RTBase64DecodedSize(const char *pszString, char **ppszEnd)
     123RTDECL(ssize_t) RTBase64DecodedSizeEx(const char *pszString, size_t cchStringMax, char **ppszEnd)
    133124{
    134125#ifdef RT_STRICT
     
    144135    AssertCompile(sizeof(char) == sizeof(uint8_t));
    145136
    146     while ((ch = *pszString))
     137    while (cchStringMax > 0 && (ch = *pszString))
    147138    {
    148139        u8 = g_au8CharToVal[ch];
     
    154145        /* advance */
    155146        pszString++;
     147        cchStringMax--;
    156148    }
    157149
     
    166158        c6Bits++;
    167159        pszString++;
    168         while ((ch = *pszString))
     160        cchStringMax--;
     161        while (cchStringMax > 0 && (ch = *pszString))
    169162        {
    170163            u8 = g_au8CharToVal[ch];
     
    177170            }
    178171            pszString++;
     172            cchStringMax--;
    179173        }
    180174        if (cbPad >= 3)
     
    216210    return cb;
    217211}
     212RT_EXPORT_SYMBOL(RTBase64DecodedSizeEx);
     213
     214
     215RTDECL(ssize_t) RTBase64DecodedSize(const char *pszString, char **ppszEnd)
     216{
     217    return RTBase64DecodedSizeEx(pszString, RTSTR_MAX, ppszEnd);
     218}
    218219RT_EXPORT_SYMBOL(RTBase64DecodedSize);
    219220
    220221
    221 /**
    222  * Decodes a Base64 encoded string into the buffer supplied by the caller.
    223  *
    224  * @returns IPRT status code.
    225  * @retval  VERR_BUFFER_OVERFLOW if the buffer is too small. pcbActual will not
    226  *          be set, nor will ppszEnd.
    227  * @retval  VERR_INVALID_BASE64_ENCODING if the encoding is wrong.
    228  *
    229  * @param   pszString       The Base64 string. Whether the entire string or
    230  *                          just the start of the string is in Base64 depends
    231  *                          on whether ppszEnd is specified or not.
    232  * @param   pvData          Where to store the decoded data.
    233  * @param   cbData          The size of the output buffer that pvData points to.
    234  * @param   pcbActual       Where to store the actual number of bytes returned.
    235  *                          Optional.
    236  * @param   ppszEnd         Indicates that the string may contain other stuff
    237  *                          after the Base64 encoded data when not NULL. Will
    238  *                          be set to point to the first char that's not part of
    239  *                          the encoding. If NULL the entire string must be part
    240  *                          of the Base64 encoded data.
    241  */
    242 RTDECL(int) RTBase64Decode(const char *pszString, void *pvData, size_t cbData, size_t *pcbActual, char **ppszEnd)
     222RTDECL(int) RTBase64DecodeEx(const char *pszString, size_t cchStringMax, void *pvData, size_t cbData,
     223                             size_t *pcbActual, char **ppszEnd)
    243224{
    244225#ifdef RT_STRICT
     
    251232    uint8_t     u8Trio[3] = { 0, 0, 0 }; /* shuts up gcc */
    252233    uint8_t    *pbData    = (uint8_t *)pvData;
    253     uint8_t     u8        = BASE64_INVALID;
     234    uint8_t     u8;
    254235    unsigned    c6Bits    = 0;
    255236    unsigned    ch;
     
    259240    {
    260241        /* The first 6-bit group. */
    261         while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
    262             pszString++;
     242        while ((u8 = cchStringMax > 0 ? g_au8CharToVal[ch = *pszString] : BASE64_INVALID) == BASE64_SPACE)
     243            pszString++, cchStringMax--;
    263244        if (u8 >= 64)
    264245        {
     
    268249        u8Trio[0] = u8 << 2;
    269250        pszString++;
     251        cchStringMax--;
    270252
    271253        /* The second 6-bit group. */
    272         while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
    273             pszString++;
     254        while ((u8 = cchStringMax > 0 ? g_au8CharToVal[ch = *pszString] : BASE64_INVALID) == BASE64_SPACE)
     255            pszString++, cchStringMax--;
    274256        if (u8 >= 64)
    275257        {
     
    280262        u8Trio[1]  = u8 << 4;
    281263        pszString++;
     264        cchStringMax--;
    282265
    283266        /* The third 6-bit group. */
    284         while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
    285             pszString++;
     267        u8 = BASE64_INVALID;
     268        while ((u8 = cchStringMax > 0 ? g_au8CharToVal[ch = *pszString] : BASE64_INVALID) == BASE64_SPACE)
     269            pszString++, cchStringMax--;
    286270        if (u8 >= 64)
    287271        {
     
    292276        u8Trio[2]  = u8 << 6;
    293277        pszString++;
     278        cchStringMax--;
    294279
    295280        /* The fourth 6-bit group. */
    296         while ((u8 = g_au8CharToVal[ch = *pszString]) == BASE64_SPACE)
    297             pszString++;
     281        u8 = BASE64_INVALID;
     282        while ((u8 = cchStringMax > 0 ? g_au8CharToVal[ch = *pszString] : BASE64_INVALID) == BASE64_SPACE)
     283            pszString++, cchStringMax--;
    298284        if (u8 >= 64)
    299285        {
     
    303289        u8Trio[2] |= u8;
    304290        pszString++;
     291        cchStringMax--;
    305292
    306293        /* flush the trio */
     
    323310        cbPad = 1;
    324311        pszString++;
    325         while ((ch = *pszString))
     312        cchStringMax--;
     313        while (cchStringMax > 0 && (ch = *pszString))
    326314        {
    327315            u8 = g_au8CharToVal[ch];
     
    333321            }
    334322            pszString++;
     323            cchStringMax--;
    335324        }
    336325        if (cbPad >= 3)
     
    399388        *pcbActual = pbData - (uint8_t *)pvData;
    400389    return VINF_SUCCESS;
     390}
     391RT_EXPORT_SYMBOL(RTBase64DecodeEx);
     392
     393
     394RTDECL(int) RTBase64Decode(const char *pszString, void *pvData, size_t cbData, size_t *pcbActual, char **ppszEnd)
     395{
     396    return RTBase64DecodeEx(pszString, RTSTR_MAX, pvData, cbData, pcbActual, ppszEnd);
    401397}
    402398RT_EXPORT_SYMBOL(RTBase64Decode);
  • trunk/src/VBox/Runtime/common/string/uniread.cpp

    r48935 r51770  
    3535#include <string.h>
    3636#include <stdlib.h>
     37#ifdef _MSC_VER
     38# include <direct.h>
     39#else
     40# include <unistd.h>
     41#endif
    3742
    3843
     
    4045*   Global Variables                                                           *
    4146*******************************************************************************/
    42 /** When set, no output is produced.  Very useful when debugging ths code. */
    43 static bool g_fQuiet = false;
    4447/** The file we're currently parsing. */
    4548static const char *g_pszCurFile;
    4649/** The current line number. */
    4750static unsigned g_iLine;
     51/** The current output file. */
     52static FILE *g_pCurOutFile;
    4853
    4954
     
    884889    //if (pInfo->???)
    885890    //    AppendFlag(pszFlags, "RTUNI_BSPACE");
     891#if 0
    886892    if (pInfo->fInvNFD_QC != 0 || pInfo->fInvNFC_QC != 0)
    887893    {
     
    894900    else if (pInfo->paDecompositionMapping && !*pInfo->pszDecompositionType)
    895901        fprintf(stderr, "uniread: U+%05X is not QC_NFX but has canonical mappings.\n", pInfo->CodePoint);
     902#endif
    896903
    897904    if (!*pszFlags)
     
    906913
    907914/**
     915 * Closes the primary output stream.
     916 */
     917static int Stream1Close(void)
     918{
     919    if (g_pCurOutFile && g_pCurOutFile != stdout && g_pCurOutFile != stderr)
     920    {
     921        if (fclose(g_pCurOutFile) != 0)
     922        {
     923            fprintf(stderr, "Error closing output file.\n");
     924            return -1;
     925        }
     926    }
     927    g_pCurOutFile = NULL;
     928    return 0;
     929}
     930
     931
     932/**
     933 * Initializes the 1st stream to output to a given file.
     934 */
     935static int Stream1Init(const char *pszName)
     936{
     937    int rc = Stream1Close();
     938    if (!rc)
     939    {
     940        g_pCurOutFile = fopen(pszName, "w");
     941        if (!g_pCurOutFile)
     942        {
     943            fprintf(stderr, "Error opening output file '%s'.\n", pszName);
     944            rc = -1;
     945        }
     946    }
     947    return rc;
     948}
     949
     950
     951/**
    908952 * printf wrapper for the primary output stream.
    909953 *
     
    917961    va_list va;
    918962    va_start(va, pszFormat);
    919     if (!g_fQuiet)
    920         cch = vfprintf(stdout, pszFormat, va);
    921     else
    922         cch = (int)strlen(pszFormat);
     963    cch = vfprintf(g_pCurOutFile, pszFormat, va);
    923964    va_end(va);
    924965    return cch;
     
    9741015 * Print the unidata.cpp file header and include list.
    9751016 */
    976 int PrintHeader(const char *argv0)
    977 {
    978     Stream1Printf("/** @file\n"
    979                   " *\n"
     1017int PrintHeader(const char *argv0, const char *pszBaseDir)
     1018{
     1019    char szBuf[1024];
     1020    if (!pszBaseDir)
     1021    {
     1022        memset(szBuf, 0, sizeof(szBuf));
     1023#ifdef _MSC_VER
     1024        _getcwd(szBuf, sizeof(szBuf));
     1025#else
     1026        getcwd(szBuf, sizeof(szBuf));
     1027#endif
     1028        pszBaseDir = szBuf;
     1029    }
     1030
     1031    Stream1Printf("/* $" "Id" "$ */\n"
     1032                  "/** @file\n"
    9801033                  " * IPRT - Unicode Tables.\n"
    9811034                  " *\n"
    982                   " * Automatically Generated by %s (" __DATE__ " " __TIME__ ")\n"
     1035                  " * Automatically Generated from %s\n"
     1036                  " * by %s (" __DATE__ " " __TIME__ ")\n"
    9831037                  " */\n"
    9841038                  "\n"
    9851039                  "/*\n"
    986                   " * Copyright (C) 2006-2010 Oracle Corporation\n"
     1040                  " * Copyright (C) 2006-2014 Oracle Corporation\n"
    9871041                  " *\n"
    9881042                  " * This file is part of VirtualBox Open Source Edition (OSE), as\n"
     
    10061060                  "#include <iprt/uni.h>\n"
    10071061                  "\n",
    1008                   argv0);
     1062                  pszBaseDir, argv0);
    10091063    return 0;
    10101064}
     
    10201074     */
    10211075    Stream2Init();
    1022     Stream2Printf("const RTUNIFLAGSRANGE g_aRTUniFlagsRanges[] =\n"
     1076    Stream2Printf("RT_DECL_DATA_CONST(const RTUNIFLAGSRANGE) g_aRTUniFlagsRanges[] =\n"
    10231077                  "{\n");
    10241078    RTUNICP i = 0;
     
    10471101            if (iStart < 0)
    10481102            {
    1049                 Stream1Printf("static const uint8_t g_afRTUniFlags0x%06x[] = \n"
     1103                Stream1Printf("static const uint8_t g_afRTUniFlags0x%06x[] =\n"
    10501104                              "{\n", i);
    10511105                iStart = i;
     
    10691123{
    10701124    Stream2Init();
    1071     Stream2Printf("const RTUNICASERANGE g_aRTUniUpperRanges[] =\n"
     1125    Stream2Printf("RT_DECL_DATA_CONST(const RTUNICASERANGE) g_aRTUniUpperRanges[] =\n"
    10721126                  "{\n");
    10731127    RTUNICP i = 0;
     
    10951149            if (iStart < 0)
    10961150            {
    1097                 Stream1Printf("static const RTUNICP g_afRTUniUpper0x%06x[] = \n"
     1151                Stream1Printf("static const RTUNICP g_afRTUniUpper0x%06x[] =\n"
    10981152                              "{\n", i);
    10991153                iStart = i;
     
    11161170{
    11171171    Stream2Init();
    1118     Stream2Printf("const RTUNICASERANGE g_aRTUniLowerRanges[] =\n"
     1172    Stream2Printf("RT_DECL_DATA_CONST(const RTUNICASERANGE) g_aRTUniLowerRanges[] =\n"
    11191173                  "{\n");
    11201174    RTUNICP i = 0;
     
    11421196            if (iStart < 0)
    11431197            {
    1144                 Stream1Printf("static const RTUNICP g_afRTUniLower0x%06x[] = \n"
     1198                Stream1Printf("static const RTUNICP g_afRTUniLower0x%06x[] =\n"
    11451199                              "{\n", i);
    11461200                iStart = i;
     
    12021256            pszBaseDir = argv[argi];
    12031257        }
    1204         else if (   !strcmp(argv[argi], "-q")
    1205                  || !strcmp(argv[argi], "--quiet"))
    1206             g_fQuiet = true;
    12071258        else
    12081259        {
     
    12321283
    12331284    /*
    1234      * Print stuff.
     1285     * Produce output files.
    12351286     */
    1236     rc = PrintHeader(argv[0]);
    1237     if (rc)
    1238         return rc;
    1239     rc = PrintFlags();
    1240     if (rc)
    1241         return rc;
    1242     rc = PrintUpper();
    1243     if (rc)
    1244         return rc;
    1245     rc = PrintLower();
    1246     if (rc)
    1247         return rc;
     1287    rc = Stream1Init("unidata-flags.cpp");
     1288    if (!rc)
     1289        rc = PrintHeader(argv[0], pszBaseDir);
     1290    if (!rc)
     1291        rc = PrintFlags();
     1292
     1293    rc = Stream1Init("unidata-upper.cpp");
     1294    if (!rc)
     1295        rc = PrintHeader(argv[0], pszBaseDir);
     1296    if (!rc)
     1297        rc = PrintUpper();
     1298
     1299    rc = Stream1Init("unidata-lower.cpp");
     1300    if (!rc)
     1301        rc = PrintHeader(argv[0], pszBaseDir);
     1302    if (!rc)
     1303        rc = PrintLower();
     1304    if (!rc)
     1305        rc = Stream1Close();
    12481306
    12491307    /* done */
    1250     fflush(stdout);
    1251 
    12521308    return rc;
    12531309}
  • trunk/src/VBox/Runtime/common/string/utf-16.cpp

    r50795 r51770  
    171171
    172172
    173 RTDECL(int) RTUtf16ICmp(register PCRTUTF16 pwsz1, register PCRTUTF16 pwsz2)
    174 {
    175     if (pwsz1 == pwsz2)
    176         return 0;
    177     if (!pwsz1)
    178         return -1;
    179     if (!pwsz2)
    180         return 1;
    181 
    182     PCRTUTF16 pwsz1Start = pwsz1; /* keep it around in case we have to backtrack on a surrogate pair */
    183     for (;;)
    184     {
    185         register RTUTF16  wc1 = *pwsz1;
    186         register RTUTF16  wc2 = *pwsz2;
    187         register int     iDiff = wc1 - wc2;
    188         if (iDiff)
    189         {
    190             /* unless they are *both* surrogate pairs, there is no chance they'll be identical. */
    191             if (    wc1 < 0xd800
    192                 ||  wc2 < 0xd800
    193                 ||  wc1 > 0xdfff
    194                 ||  wc2 > 0xdfff)
    195             {
    196                 /* simple UCS-2 char */
    197                 iDiff = RTUniCpToUpper(wc1) - RTUniCpToUpper(wc2);
    198                 if (iDiff)
    199                     iDiff = RTUniCpToLower(wc1) - RTUniCpToLower(wc2);
    200             }
    201             else
    202             {
    203                 /* a damned pair */
    204                 RTUNICP uc1;
    205                 RTUNICP uc2;
    206                 if (wc1 >= 0xdc00)
    207                 {
    208                     if (pwsz1Start == pwsz1)
    209                         return iDiff;
    210                     uc1 = pwsz1[-1];
    211                     if (uc1 < 0xd800 || uc1 >= 0xdc00)
    212                         return iDiff;
    213                     uc1 = 0x10000 + (((uc1       & 0x3ff) << 10) | (wc1 & 0x3ff));
    214                     uc2 = 0x10000 + (((pwsz2[-1] & 0x3ff) << 10) | (wc2 & 0x3ff));
    215                 }
    216                 else
    217                 {
    218                     uc1 = *++pwsz1;
    219                     if (uc1 < 0xdc00 || uc1 >= 0xe000)
    220                         return iDiff;
    221                     uc1 = 0x10000 + (((wc1 & 0x3ff) << 10) | (uc1      & 0x3ff));
    222                     uc2 = 0x10000 + (((wc2 & 0x3ff) << 10) | (*++pwsz2 & 0x3ff));
    223                 }
    224                 iDiff = RTUniCpToUpper(uc1) - RTUniCpToUpper(uc2);
    225                 if (iDiff)
    226                     iDiff = RTUniCpToLower(uc1) - RTUniCpToLower(uc2); /* serious paranoia! */
    227             }
    228             if (iDiff)
    229                 return iDiff;
    230         }
    231         if (!wc1)
    232             return 0;
    233         pwsz1++;
    234         pwsz2++;
    235     }
    236 }
    237 RT_EXPORT_SYMBOL(RTUtf16ICmp);
    238 
    239 
    240 RTDECL(PRTUTF16) RTUtf16ToLower(PRTUTF16 pwsz)
    241 {
    242     PRTUTF16 pwc = pwsz;
    243     for (;;)
    244     {
    245         RTUTF16 wc = *pwc;
    246         if (!wc)
    247             break;
    248         if (wc < 0xd800 || wc >= 0xdc00)
    249         {
    250             RTUNICP ucFolded = RTUniCpToLower(wc);
    251             if (ucFolded < 0x10000)
    252                 *pwc++ = RTUniCpToLower(wc);
    253         }
    254         else
    255         {
    256             /* surrogate */
    257             RTUTF16 wc2 = pwc[1];
    258             if (wc2 >= 0xdc00 && wc2 <= 0xdfff)
    259             {
    260                 RTUNICP uc = 0x10000 + (((wc & 0x3ff) << 10) | (wc2 & 0x3ff));
    261                 RTUNICP ucFolded = RTUniCpToLower(uc);
    262                 if (uc != ucFolded && ucFolded >= 0x10000) /* we don't support shrinking the string */
    263                 {
    264                     uc -= 0x10000;
    265                     *pwc++ = 0xd800 | (uc >> 10);
    266                     *pwc++ = 0xdc00 | (uc & 0x3ff);
    267                 }
    268             }
    269             else /* invalid encoding. */
    270                 pwc++;
    271         }
    272     }
    273     return pwsz;
    274 }
    275 RT_EXPORT_SYMBOL(RTUtf16ToLower);
    276 
    277 
    278 RTDECL(PRTUTF16) RTUtf16ToUpper(PRTUTF16 pwsz)
    279 {
    280     PRTUTF16 pwc = pwsz;
    281     for (;;)
    282     {
    283         RTUTF16 wc = *pwc;
    284         if (!wc)
    285             break;
    286         if (wc < 0xd800 || wc >= 0xdc00)
    287             *pwc++ = RTUniCpToUpper(wc);
    288         else
    289         {
    290             /* surrogate */
    291             RTUTF16 wc2 = pwc[1];
    292             if (wc2 >= 0xdc00 && wc2 <= 0xdfff)
    293             {
    294                 RTUNICP uc = 0x10000 + (((wc & 0x3ff) << 10) | (wc2 & 0x3ff));
    295                 RTUNICP ucFolded = RTUniCpToUpper(uc);
    296                 if (uc != ucFolded && ucFolded >= 0x10000) /* we don't support shrinking the string */
    297                 {
    298                     uc -= 0x10000;
    299                     *pwc++ = 0xd800 | (uc >> 10);
    300                     *pwc++ = 0xdc00 | (uc & 0x3ff);
    301                 }
    302             }
    303             else /* invalid encoding. */
    304                 pwc++;
    305         }
    306     }
    307     return pwsz;
    308 }
    309 RT_EXPORT_SYMBOL(RTUtf16ToUpper);
    310 
    311 
    312173RTDECL(int) RTUtf16ValidateEncoding(PCRTUTF16 pwsz)
    313174{
     
    786647RT_EXPORT_SYMBOL(RTUtf16PutCpInternal);
    787648
    788 
    789 /**
    790  * Validate the UTF-16 encoding and calculates the length of a Latin1 encoding.
    791  *
    792  * @returns iprt status code.
    793  * @param   pwsz        The UTF-16 string.
    794  * @param   cwc         The max length of the UTF-16 string to consider.
    795  * @param   pcch        Where to store the length (excluding '\\0') of the Latin1 string. (cch == cb, btw)
    796  */
    797 static int rtUtf16CalcLatin1Length(PCRTUTF16 pwsz, size_t cwc, size_t *pcch)
    798 {
    799     int     rc = VINF_SUCCESS;
    800     size_t  cch = 0;
    801     while (cwc > 0)
    802     {
    803         RTUTF16 wc = *pwsz++; cwc--;
    804         if (!wc)
    805             break;
    806         else if (RT_LIKELY(wc < 0x100))
    807             ++cch;
    808         else
    809         {
    810             if (wc < 0xd800 || wc > 0xdfff)
    811             {
    812                 if (wc >= 0xfffe)
    813                 {
    814                     RTStrAssertMsgFailed(("endian indicator! wc=%#x\n", wc));
    815                     rc = VERR_CODE_POINT_ENDIAN_INDICATOR;
    816                     break;
    817                 }
    818             }
    819             else
    820             {
    821                 if (wc >= 0xdc00)
    822                 {
    823                     RTStrAssertMsgFailed(("Wrong 1st char in surrogate! wc=%#x\n", wc));
    824                     rc = VERR_INVALID_UTF16_ENCODING;
    825                     break;
    826                 }
    827                 if (cwc <= 0)
    828                 {
    829                     RTStrAssertMsgFailed(("Invalid length! wc=%#x\n", wc));
    830                     rc = VERR_INVALID_UTF16_ENCODING;
    831                     break;
    832                 }
    833                 wc = *pwsz++; cwc--;
    834                 if (wc < 0xdc00 || wc > 0xdfff)
    835                 {
    836                     RTStrAssertMsgFailed(("Wrong 2nd char in surrogate! wc=%#x\n", wc));
    837                     rc = VERR_INVALID_UTF16_ENCODING;
    838                     break;
    839                 }
    840             }
    841 
    842             rc = VERR_NO_TRANSLATION;
    843             break;
    844         }
    845     }
    846 
    847     /* done */
    848     *pcch = cch;
    849     return rc;
    850 }
    851 
    852 
    853 /**
    854  * Recodes an valid UTF-16 string as Latin1.
    855  *
    856  * @returns iprt status code.
    857  * @param   pwsz        The UTF-16 string.
    858  * @param   cwc         The number of RTUTF16 characters to process from pwsz. The recoding
    859  *                      will stop when cwc or '\\0' is reached.
    860  * @param   psz         Where to store the Latin1 string.
    861  * @param   cch         The size of the Latin1 buffer, excluding the terminator.
    862  */
    863 static int rtUtf16RecodeAsLatin1(PCRTUTF16 pwsz, size_t cwc, char *psz, size_t cch)
    864 {
    865     unsigned char  *pch = (unsigned char *)psz;
    866     int             rc  = VINF_SUCCESS;
    867     while (cwc > 0)
    868     {
    869         RTUTF16 wc = *pwsz++; cwc--;
    870         if (!wc)
    871             break;
    872         if (RT_LIKELY(wc < 0x100))
    873         {
    874             if (RT_UNLIKELY(cch < 1))
    875             {
    876                 RTStrAssertMsgFailed(("Buffer overflow! 1\n"));
    877                 rc = VERR_BUFFER_OVERFLOW;
    878                 break;
    879             }
    880             cch--;
    881             *pch++ = (unsigned char)wc;
    882         }
    883         else
    884         {
    885             if (wc < 0xd800 || wc > 0xdfff)
    886             {
    887                 if (wc >= 0xfffe)
    888                 {
    889                     RTStrAssertMsgFailed(("endian indicator! wc=%#x\n", wc));
    890                     rc = VERR_CODE_POINT_ENDIAN_INDICATOR;
    891                     break;
    892                 }
    893             }
    894             else
    895             {
    896                 if (wc >= 0xdc00)
    897                 {
    898                     RTStrAssertMsgFailed(("Wrong 1st char in surrogate! wc=%#x\n", wc));
    899                     rc = VERR_INVALID_UTF16_ENCODING;
    900                     break;
    901                 }
    902                 if (cwc <= 0)
    903                 {
    904                     RTStrAssertMsgFailed(("Invalid length! wc=%#x\n", wc));
    905                     rc = VERR_INVALID_UTF16_ENCODING;
    906                     break;
    907                 }
    908                 RTUTF16 wc2 = *pwsz++; cwc--;
    909                 if (wc2 < 0xdc00 || wc2 > 0xdfff)
    910                 {
    911                     RTStrAssertMsgFailed(("Wrong 2nd char in surrogate! wc=%#x\n", wc));
    912                     rc = VERR_INVALID_UTF16_ENCODING;
    913                     break;
    914                 }
    915             }
    916 
    917             rc = VERR_NO_TRANSLATION;
    918             break;
    919         }
    920     }
    921 
    922     /* done */
    923     *pch = '\0';
    924     return rc;
    925 }
    926 
    927 
    928 RTDECL(int)  RTUtf16ToLatin1Tag(PCRTUTF16 pwszString, char **ppszString, const char *pszTag)
    929 {
    930     /*
    931      * Validate input.
    932      */
    933     Assert(VALID_PTR(ppszString));
    934     Assert(VALID_PTR(pwszString));
    935     *ppszString = NULL;
    936 
    937     /*
    938      * Validate the UTF-16 string and calculate the length of the UTF-8 encoding of it.
    939      */
    940     size_t cch;
    941     int rc = rtUtf16CalcLatin1Length(pwszString, RTSTR_MAX, &cch);
    942     if (RT_SUCCESS(rc))
    943     {
    944         /*
    945          * Allocate buffer and recode it.
    946          */
    947         char *pszResult = (char *)RTMemAllocTag(cch + 1, pszTag);
    948         if (pszResult)
    949         {
    950             rc = rtUtf16RecodeAsLatin1(pwszString, RTSTR_MAX, pszResult, cch);
    951             if (RT_SUCCESS(rc))
    952             {
    953                 *ppszString = pszResult;
    954                 return rc;
    955             }
    956 
    957             RTMemFree(pszResult);
    958         }
    959         else
    960             rc = VERR_NO_STR_MEMORY;
    961     }
    962     return rc;
    963 }
    964 RT_EXPORT_SYMBOL(RTUtf16ToLatin1Tag);
    965 
    966 
    967 RTDECL(int)  RTUtf16ToLatin1ExTag(PCRTUTF16 pwszString, size_t cwcString, char **ppsz, size_t cch, size_t *pcch, const char *pszTag)
    968 {
    969     /*
    970      * Validate input.
    971      */
    972     AssertPtr(pwszString);
    973     AssertPtr(ppsz);
    974     AssertPtrNull(pcch);
    975 
    976     /*
    977      * Validate the UTF-16 string and calculate the length of the Latin1 encoding of it.
    978      */
    979     size_t cchResult;
    980     int rc = rtUtf16CalcLatin1Length(pwszString, cwcString, &cchResult);
    981     if (RT_SUCCESS(rc))
    982     {
    983         if (pcch)
    984             *pcch = cchResult;
    985 
    986         /*
    987          * Check buffer size / Allocate buffer and recode it.
    988          */
    989         bool fShouldFree;
    990         char *pszResult;
    991         if (cch > 0 && *ppsz)
    992         {
    993             fShouldFree = false;
    994             if (cch <= cchResult)
    995                 return VERR_BUFFER_OVERFLOW;
    996             pszResult = *ppsz;
    997         }
    998         else
    999         {
    1000             *ppsz = NULL;
    1001             fShouldFree = true;
    1002             cch = RT_MAX(cch, cchResult + 1);
    1003             pszResult = (char *)RTMemAllocTag(cch, pszTag);
    1004         }
    1005         if (pszResult)
    1006         {
    1007             rc = rtUtf16RecodeAsLatin1(pwszString, cwcString, pszResult, cch - 1);
    1008             if (RT_SUCCESS(rc))
    1009             {
    1010                 *ppsz = pszResult;
    1011                 return rc;
    1012             }
    1013 
    1014             if (fShouldFree)
    1015                 RTMemFree(pszResult);
    1016         }
    1017         else
    1018             rc = VERR_NO_STR_MEMORY;
    1019     }
    1020     return rc;
    1021 }
    1022 RT_EXPORT_SYMBOL(RTUtf16ToLatin1ExTag);
    1023 
    1024 
    1025 RTDECL(size_t) RTUtf16CalcLatin1Len(PCRTUTF16 pwsz)
    1026 {
    1027     size_t cch;
    1028     int rc = rtUtf16CalcLatin1Length(pwsz, RTSTR_MAX, &cch);
    1029     return RT_SUCCESS(rc) ? cch : 0;
    1030 }
    1031 RT_EXPORT_SYMBOL(RTUtf16CalcLatin1Len);
    1032 
    1033 
    1034 RTDECL(int) RTUtf16CalcLatin1LenEx(PCRTUTF16 pwsz, size_t cwc, size_t *pcch)
    1035 {
    1036     size_t cch;
    1037     int rc = rtUtf16CalcLatin1Length(pwsz, cwc, &cch);
    1038     if (pcch)
    1039         *pcch = RT_SUCCESS(rc) ? cch : ~(size_t)0;
    1040     return rc;
    1041 }
    1042 RT_EXPORT_SYMBOL(RTUtf16CalcLatin1LenEx);
    1043 
    1044 
    1045 /**
    1046  * Calculates the UTF-16 length of a Latin1 string.  In fact this is just the
    1047  * original length, but the function saves us nasty comments to that effect
    1048  * all over the place.
    1049  *
    1050  * @returns IPRT status code.
    1051  * @param   psz     Pointer to the Latin1 string.
    1052  * @param   cch     The max length of the string. (btw cch = cb)
    1053  *                  Use RTSTR_MAX if all of the string is to be examined.s
    1054  * @param   pcwc    Where to store the length of the UTF-16 string as a number of RTUTF16 characters.
    1055  */
    1056 static int rtLatin1CalcUtf16Length(const char *psz, size_t cch, size_t *pcwc)
    1057 {
    1058     *pcwc = RTStrNLen(psz, cch);
    1059     return VINF_SUCCESS;
    1060 }
    1061 
    1062 
    1063 /**
    1064  * Recodes a Latin1 string as UTF-16.  This is just a case of expanding it to
    1065  * sixteen bits, as Unicode is a superset of Latin1.
    1066  *
    1067  * Since we know the input is valid, we do *not* perform length checks.
    1068  *
    1069  * @returns iprt status code.
    1070  * @param   psz     The Latin1 string to recode.
    1071  * @param   cch     The number of chars (the type char, so bytes if you like) to process of the Latin1 string.
    1072  *                  The recoding will stop when cch or '\\0' is reached. Pass RTSTR_MAX to process up to '\\0'.
    1073  * @param   pwsz    Where to store the UTF-16 string.
    1074  * @param   cwc     The number of RTUTF16 items the pwsz buffer can hold, excluding the terminator ('\\0').
    1075  */
    1076 static int rtLatin1RecodeAsUtf16(const char *psz, size_t cch, PRTUTF16 pwsz, size_t cwc)
    1077 {
    1078     int                     rc   = VINF_SUCCESS;
    1079     const unsigned char    *puch = (const unsigned char *)psz;
    1080     PRTUTF16                pwc  = pwsz;
    1081     while (cch-- > 0)
    1082     {
    1083         /* read the next char and check for terminator. */
    1084         const unsigned char uch = *puch;
    1085         if (!uch)
    1086             break;
    1087 
    1088         /* check for output overflow */
    1089         if (RT_UNLIKELY(cwc < 1))
    1090         {
    1091             rc = VERR_BUFFER_OVERFLOW;
    1092             break;
    1093         }
    1094 
    1095         /* expand the code point */
    1096         *pwc++ = uch;
    1097         cwc--;
    1098         puch++;
    1099     }
    1100 
    1101     /* done */
    1102     *pwc = '\0';
    1103     return rc;
    1104 }
    1105 
    1106 
    1107 RTDECL(int) RTLatin1ToUtf16Tag(const char *pszString, PRTUTF16 *ppwszString, const char *pszTag)
    1108 {
    1109     /*
    1110      * Validate input.
    1111      */
    1112     Assert(VALID_PTR(ppwszString));
    1113     Assert(VALID_PTR(pszString));
    1114     *ppwszString = NULL;
    1115 
    1116     /*
    1117      * Validate the input and calculate the length of the UTF-16 string.
    1118      */
    1119     size_t cwc;
    1120     int rc = rtLatin1CalcUtf16Length(pszString, RTSTR_MAX, &cwc);
    1121     if (RT_SUCCESS(rc))
    1122     {
    1123         /*
    1124          * Allocate buffer.
    1125          */
    1126         PRTUTF16 pwsz = (PRTUTF16)RTMemAllocTag((cwc + 1) * sizeof(RTUTF16), pszTag);
    1127         if (pwsz)
    1128         {
    1129             /*
    1130              * Encode the UTF-16 string.
    1131              */
    1132             rc = rtLatin1RecodeAsUtf16(pszString, RTSTR_MAX, pwsz, cwc);
    1133             if (RT_SUCCESS(rc))
    1134             {
    1135                 *ppwszString = pwsz;
    1136                 return rc;
    1137             }
    1138             RTMemFree(pwsz);
    1139         }
    1140         else
    1141             rc = VERR_NO_UTF16_MEMORY;
    1142     }
    1143     return rc;
    1144 }
    1145 RT_EXPORT_SYMBOL(RTLatin1ToUtf16Tag);
    1146 
    1147 
    1148 RTDECL(int)  RTLatin1ToUtf16ExTag(const char *pszString, size_t cchString,
    1149                                   PRTUTF16 *ppwsz, size_t cwc, size_t *pcwc, const char *pszTag)
    1150 {
    1151     /*
    1152      * Validate input.
    1153      */
    1154     Assert(VALID_PTR(pszString));
    1155     Assert(VALID_PTR(ppwsz));
    1156     Assert(!pcwc || VALID_PTR(pcwc));
    1157 
    1158     /*
    1159      * Validate the input and calculate the length of the UTF-16 string.
    1160      */
    1161     size_t cwcResult;
    1162     int rc = rtLatin1CalcUtf16Length(pszString, cchString, &cwcResult);
    1163     if (RT_SUCCESS(rc))
    1164     {
    1165         if (pcwc)
    1166             *pcwc = cwcResult;
    1167 
    1168         /*
    1169          * Check buffer size / Allocate buffer.
    1170          */
    1171         bool fShouldFree;
    1172         PRTUTF16 pwszResult;
    1173         if (cwc > 0 && *ppwsz)
    1174         {
    1175             fShouldFree = false;
    1176             if (cwc <= cwcResult)
    1177                 return VERR_BUFFER_OVERFLOW;
    1178             pwszResult = *ppwsz;
    1179         }
    1180         else
    1181         {
    1182             *ppwsz = NULL;
    1183             fShouldFree = true;
    1184             cwc = RT_MAX(cwcResult + 1, cwc);
    1185             pwszResult = (PRTUTF16)RTMemAllocTag(cwc * sizeof(RTUTF16), pszTag);
    1186         }
    1187         if (pwszResult)
    1188         {
    1189             /*
    1190              * Encode the UTF-16 string.
    1191              */
    1192             rc = rtLatin1RecodeAsUtf16(pszString, cchString, pwszResult, cwc - 1);
    1193             if (RT_SUCCESS(rc))
    1194             {
    1195                 *ppwsz = pwszResult;
    1196                 return rc;
    1197             }
    1198             if (fShouldFree)
    1199                 RTMemFree(pwszResult);
    1200         }
    1201         else
    1202             rc = VERR_NO_UTF16_MEMORY;
    1203     }
    1204     return rc;
    1205 }
    1206 RT_EXPORT_SYMBOL(RTLatin1ToUtf16ExTag);
    1207 
    1208 
    1209 RTDECL(size_t) RTLatin1CalcUtf16Len(const char *psz)
    1210 {
    1211     size_t cwc;
    1212     int rc = rtLatin1CalcUtf16Length(psz, RTSTR_MAX, &cwc);
    1213     return RT_SUCCESS(rc) ? cwc : 0;
    1214 }
    1215 RT_EXPORT_SYMBOL(RTLatin1CalcUtf16Len);
    1216 
    1217 
    1218 RTDECL(int) RTLatin1CalcUtf16LenEx(const char *psz, size_t cch, size_t *pcwc)
    1219 {
    1220     size_t cwc;
    1221     int rc = rtLatin1CalcUtf16Length(psz, cch, &cwc);
    1222     if (pcwc)
    1223         *pcwc = RT_SUCCESS(rc) ? cwc : ~(size_t)0;
    1224     return rc;
    1225 }
    1226 RT_EXPORT_SYMBOL(RTLatin1CalcUtf16LenEx);
  • trunk/src/VBox/Runtime/common/string/utf-8-case.cpp

    r48935 r51770  
    11/* $Id$ */
    22/** @file
    3  * IPRT - UTF-8 Case Sensitivity and Folding.
     3 * IPRT - UTF-8 Case Sensitivity and Folding, Part 1.
    44 */
    55
     
    339339RT_EXPORT_SYMBOL(RTStrToUpper);
    340340
    341 
    342 RTDECL(bool) RTStrIsCaseFoldable(const char *psz)
    343 {
    344     /*
    345      * Loop the code points in the string, checking them one by one until we
    346      * find something that can be folded.
    347      */
    348     RTUNICP uc;
    349     do
    350     {
    351         int rc = RTStrGetCpEx(&psz, &uc);
    352         if (RT_SUCCESS(rc))
    353         {
    354             if (RTUniCpIsFoldable(uc))
    355                 return true;
    356         }
    357         else
    358         {
    359             /* bad encoding, just skip it quietly (uc == RTUNICP_INVALID (!= 0)). */
    360             AssertRC(rc);
    361         }
    362     } while (uc != 0);
    363 
    364     return false;
    365 }
    366 RT_EXPORT_SYMBOL(RTStrIsCaseFoldable);
    367 
    368 
    369 RTDECL(bool) RTStrIsUpperCased(const char *psz)
    370 {
    371     /*
    372      * Check that there are no lower case chars in the string.
    373      */
    374     RTUNICP uc;
    375     do
    376     {
    377         int rc = RTStrGetCpEx(&psz, &uc);
    378         if (RT_SUCCESS(rc))
    379         {
    380             if (RTUniCpIsLower(uc))
    381                 return false;
    382         }
    383         else
    384         {
    385             /* bad encoding, just skip it quietly (uc == RTUNICP_INVALID (!= 0)). */
    386             AssertRC(rc);
    387         }
    388     } while (uc != 0);
    389 
    390     return true;
    391 }
    392 RT_EXPORT_SYMBOL(RTStrIsUpperCased);
    393 
    394 
    395 RTDECL(bool) RTStrIsLowerCased(const char *psz)
    396 {
    397     /*
    398      * Check that there are no lower case chars in the string.
    399      */
    400     RTUNICP uc;
    401     do
    402     {
    403         int rc = RTStrGetCpEx(&psz, &uc);
    404         if (RT_SUCCESS(rc))
    405         {
    406             if (RTUniCpIsUpper(uc))
    407                 return false;
    408         }
    409         else
    410         {
    411             /* bad encoding, just skip it quietly (uc == RTUNICP_INVALID (!= 0)). */
    412             AssertRC(rc);
    413         }
    414     } while (uc != 0);
    415 
    416     return true;
    417 }
    418 RT_EXPORT_SYMBOL(RTStrIsLowerCased);
    419 
  • trunk/src/VBox/Runtime/include/internal/ldr.h

    r49044 r51770  
    323323    DECLCALLBACKMEMBER(int, pfnReadDbgInfo)(PRTLDRMODINTERNAL pMod, uint32_t iDbgInfo, RTFOFF off, size_t cb, void *pvBuf);
    324324
    325 
    326 
    327325    /**
    328326     * Generic method for querying image properties.
     
    338336     * @param   cbBuf           The size of the return buffer (valid as per
    339337     *                          property).
    340      */
    341     DECLCALLBACKMEMBER(int, pfnQueryProp)(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf);
     338     * @param   pcbRet          The number of bytes actually returned.  If
     339     *                          VERR_BUFFER_OVERFLOW is returned, this is set to the
     340     *                          required buffer size.
     341     */
     342    DECLCALLBACKMEMBER(int, pfnQueryProp)(PRTLDRMODINTERNAL pMod, RTLDRPROP enmProp, void *pvBuf, size_t cbBuf, size_t *pcbRet);
     343
     344    /**
     345     * Verify the image signature.
     346     *
     347     * This may permform additional integrity checks on the image structures that
     348     * was not done when opening the image.
     349     *
     350     * @returns IPRT status code.
     351     * @retval  VERR_LDRVI_NOT_SIGNED if not signed.
     352     *
     353     * @param   pMod            Pointer to the loader module structure.
     354     * @param   pfnCallback     Callback that does the signature and certificate
     355     *                          verficiation.
     356     * @param   pvUser          User argument for the callback.
     357     * @param   pErrInfo        Pointer to an error info buffer. Optional.
     358     */
     359    DECLCALLBACKMEMBER(int, pfnVerifySignature)(PRTLDRMODINTERNAL pMod, PFNRTLDRVALIDATESIGNEDDATA pfnCallback, void *pvUser,
     360                                                PRTERRINFO pErrInfo);
     361
     362    /**
     363     * Calculate the image hash according the image signing rules.
     364     *
     365     * @returns IPRT status code.
     366     * @param   hLdrMod         The module handle.
     367     * @param   enmDigest       Which kind of digest.
     368     * @param   pszDigest       Where to store the image digest.
     369     * @param   cbDigest        Size of the buffer @a pszDigest points at.
     370     */
     371    DECLCALLBACKMEMBER(int, pfnHashImage)(PRTLDRMODINTERNAL pMod, RTDIGESTTYPE enmDigest, char *pszDigest, size_t cbDigest);
    342372
    343373    /** Dummy entry to make sure we've initialized it all. */
     
    346376typedef RTLDROPS *PRTLDROPS;
    347377typedef const RTLDROPS *PCRTLDROPS;
    348 
    349 
    350 /** Pointer to a loader reader instance. */
    351 typedef struct RTLDRREADER *PRTLDRREADER;
    352 
    353 /**
    354  * Loader image reader instance.
    355  * The reader will have extra data members following this structure.
    356  */
    357 typedef struct RTLDRREADER
    358 {
    359     /** The name of the image provider. */
    360     const char *pszName;
    361 
    362     /**
    363      * Reads bytes at a give place in the raw image.
    364      *
    365      * @returns iprt status code.
    366      * @param   pReader     Pointer to the reader instance.
    367      * @param   pvBuf       Where to store the bits.
    368      * @param   cb          Number of bytes to read.
    369      * @param   off         Where to start reading relative to the start of the raw image.
    370      */
    371     DECLCALLBACKMEMBER(int, pfnRead)(PRTLDRREADER pReader, void *pvBuf, size_t cb, RTFOFF off);
    372 
    373     /**
    374      * Tells end position of last read.
    375      *
    376      * @returns position relative to start of the raw image.
    377      * @param   pReader     Pointer to the reader instance.
    378      */
    379     DECLCALLBACKMEMBER(RTFOFF, pfnTell)(PRTLDRREADER pReader);
    380 
    381     /**
    382      * Gets the size of the raw image bits.
    383      *
    384      * @returns size of raw image bits in bytes.
    385      * @param   pReader     Pointer to the reader instance.
    386      */
    387     DECLCALLBACKMEMBER(RTFOFF, pfnSize)(PRTLDRREADER pReader);
    388 
    389     /**
    390      * Map the bits into memory.
    391      *
    392      * The mapping will be freed upon calling pfnDestroy() if not pfnUnmap()
    393      * is called before that. The mapping is read only.
    394      *
    395      * @returns iprt status code.
    396      * @param   pReader     Pointer to the reader instance.
    397      * @param   ppvBits     Where to store the address of the memory mapping on success.
    398      *                      The size of the mapping can be obtained by calling pfnSize().
    399      */
    400     DECLCALLBACKMEMBER(int, pfnMap)(PRTLDRREADER pReader, const void **ppvBits);
    401 
    402     /**
    403      * Unmap bits.
    404      *
    405      * @returns iprt status code.
    406      * @param   pReader     Pointer to the reader instance.
    407      * @param   pvBits      Memory pointer returned by pfnMap().
    408      */
    409     DECLCALLBACKMEMBER(int, pfnUnmap)(PRTLDRREADER pReader, const void *pvBits);
    410 
    411     /**
    412      * Gets the most appropriate log name.
    413      *
    414      * @returns Pointer to readonly log name.
    415      * @param   pReader     Pointer to the reader instance.
    416      */
    417     DECLCALLBACKMEMBER(const char *, pfnLogName)(PRTLDRREADER pReader);
    418 
    419     /**
    420      * Releases all resources associated with the reader instance.
    421      * The instance is invalid after this call returns.
    422      *
    423      * @returns iprt status code.
    424      * @param   pReader     Pointer to the reader instance.
    425      */
    426     DECLCALLBACKMEMBER(int, pfnDestroy)(PRTLDRREADER pReader);
    427 
    428 } RTLDRREADER;
    429378
    430379
     
    466415}
    467416
    468 int rtldrOpenWithReader(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phMod);
    469 
    470417
    471418/**
     
    511458int rtldrNativeLoadSystem(const char *pszFilename, const char *pszExt, uint32_t fFlags, PRTLDRMOD phLdrMod);
    512459
    513 int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs, PRTLDRMOD phLdrMod);
    514 int rtldrELFOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod);
    515 int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod);
     460int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo);
     461int rtldrELFOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo);
     462int rtldrkLdrOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, PRTLDRMOD phLdrMod, PRTERRINFO pErrInfo);
    516463/*int rtldrLXOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offLX, PRTLDRMOD phLdrMod);
    517464int rtldrMachoOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offSomething, PRTLDRMOD phLdrMod);*/
  • trunk/src/VBox/Runtime/include/internal/ldrPE.h

    r46278 r51770  
    7373#define  IMAGE_SUBSYSTEM_POSIX_CUI  0x7
    7474
    75 #define  IMAGE_LIBRARY_PROCESS_INIT  0x0001
    76 #define  IMAGE_LIBRARY_PROCESS_TERM  0x0002
    77 #define  IMAGE_LIBRARY_THREAD_INIT  0x0004
    78 #define  IMAGE_LIBRARY_THREAD_TERM  0x0008
    79 #define  IMAGE_DLLCHARACTERISTICS_NO_ISOLATION  0x0200
    80 #define  IMAGE_DLLCHARACTERISTICS_NO_SEH  0x0400
    81 #define  IMAGE_DLLCHARACTERISTICS_NO_BIND  0x0800
    82 #define  IMAGE_DLLCHARACTERISTICS_WDM_DRIVER  0x2000
    83 #define  IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE  0x8000
     75#define  IMAGE_LIBRARY_PROCESS_INIT                         0x0001
     76#define  IMAGE_LIBRARY_PROCESS_TERM                         0x0002
     77#define  IMAGE_LIBRARY_THREAD_INIT                          0x0004
     78#define  IMAGE_LIBRARY_THREAD_TERM                          0x0008
     79#define  IMAGE_DLLCHARACTERISTICS_RESERVED                  0x0010
     80#define  IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA           0x0020
     81#define  IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE              0x0040
     82#define  IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY           0x0080
     83#define  IMAGE_DLLCHARACTERISTICS_NX_COMPAT                 0x0100
     84#define  IMAGE_DLLCHARACTERISTICS_NO_ISOLATION              0x0200
     85#define  IMAGE_DLLCHARACTERISTICS_NO_SEH                    0x0400
     86#define  IMAGE_DLLCHARACTERISTICS_NO_BIND                   0x0800
     87#define  IMAGE_DLLCHARACTERISTICS_APPCONTAINER              0x1000
     88#define  IMAGE_DLLCHARACTERISTICS_WDM_DRIVER                0x2000
     89#define  IMAGE_DLLCHARACTERISTICS_GUARD_CF                  0x4000
     90#define  IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE     0x8000
    8491
    8592#define  IMAGE_NUMBEROF_DIRECTORY_ENTRIES  0x10
     
    208215#define  WIN_CERT_TYPE_EFI_GUID             UINT16_C(0x0ef1)
    209216
     217/** The alignment of the certificate table.
     218 * @remarks Found thru signtool experiments.  */
     219#define  WIN_CERTIFICATE_ALIGNMENT          8
    210220
    211221/* For .DBG files. */
     
    517527
    518528
    519 typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY32
     529
     530/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     531/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     532/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     533/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     534/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     535/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     536/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     537/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     538/* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
     539#pragma pack()
     540
     541
     542
     543typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY32_V1
     544{
     545    uint32_t  Size;
     546    uint32_t  TimeDateStamp;
     547    uint16_t  MajorVersion;
     548    uint16_t  MinorVersion;
     549    uint32_t  GlobalFlagsClear;
     550    uint32_t  GlobalFlagsSet;
     551    uint32_t  CriticalSectionDefaultTimeout;
     552    uint32_t  DeCommitFreeBlockThreshold;
     553    uint32_t  DeCommitTotalFreeThreshold;
     554    uint32_t  LockPrefixTable;
     555    uint32_t  MaximumAllocationSize;
     556    uint32_t  VirtualMemoryThreshold;
     557    uint32_t  ProcessHeapFlags;
     558    uint32_t  ProcessAffinityMask;
     559    uint16_t  CSDVersion;
     560    uint16_t  Reserved1;
     561    uint32_t  EditList;
     562    uint32_t  SecurityCookie;
     563} IMAGE_LOAD_CONFIG_DIRECTORY32_V1;
     564AssertCompileSize(IMAGE_LOAD_CONFIG_DIRECTORY32_V1, 0x40);
     565typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V1 *PIMAGE_LOAD_CONFIG_DIRECTORY32_V1;
     566typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V1 const *PCIMAGE_LOAD_CONFIG_DIRECTORY32_V1;
     567
     568typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY32_V2
    520569{
    521570    uint32_t  Size;
     
    539588    uint32_t  SEHandlerTable;
    540589    uint32_t  SEHandlerCount;
    541 } IMAGE_LOAD_CONFIG_DIRECTORY32;
    542 typedef IMAGE_LOAD_CONFIG_DIRECTORY32 *PIMAGE_LOAD_CONFIG_DIRECTORY32;
    543 typedef IMAGE_LOAD_CONFIG_DIRECTORY32 const *PCIMAGE_LOAD_CONFIG_DIRECTORY32;
    544 
    545 typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY64
     590} IMAGE_LOAD_CONFIG_DIRECTORY32_V2;
     591AssertCompileSize(IMAGE_LOAD_CONFIG_DIRECTORY32_V2, 0x48);
     592typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V2 *PIMAGE_LOAD_CONFIG_DIRECTORY32_V2;
     593typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V2 const *PCIMAGE_LOAD_CONFIG_DIRECTORY32_V2;
     594
     595typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY32_V3
     596{
     597    uint32_t  Size;
     598    uint32_t  TimeDateStamp;
     599    uint16_t  MajorVersion;
     600    uint16_t  MinorVersion;
     601    uint32_t  GlobalFlagsClear;
     602    uint32_t  GlobalFlagsSet;
     603    uint32_t  CriticalSectionDefaultTimeout;
     604    uint32_t  DeCommitFreeBlockThreshold;
     605    uint32_t  DeCommitTotalFreeThreshold;
     606    uint32_t  LockPrefixTable;
     607    uint32_t  MaximumAllocationSize;
     608    uint32_t  VirtualMemoryThreshold;
     609    uint32_t  ProcessHeapFlags;
     610    uint32_t  ProcessAffinityMask;
     611    uint16_t  CSDVersion;
     612    uint16_t  Reserved1;
     613    uint32_t  EditList;
     614    uint32_t  SecurityCookie;
     615    uint32_t  SEHandlerTable;
     616    uint32_t  SEHandlerCount;
     617    uint32_t  GuardCFCCheckFunctionPointer;
     618    uint32_t  Reserved2;
     619    uint32_t  GuardCFFunctionTable;
     620    uint32_t  GuardCFFunctionCount;
     621    uint32_t  GuardFlags;
     622} IMAGE_LOAD_CONFIG_DIRECTORY32_V3;
     623AssertCompileSize(IMAGE_LOAD_CONFIG_DIRECTORY32_V3, 0x5c);
     624typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V3 *PIMAGE_LOAD_CONFIG_DIRECTORY32_V3;
     625typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V3 const *PCIMAGE_LOAD_CONFIG_DIRECTORY32_V3;
     626
     627typedef IMAGE_LOAD_CONFIG_DIRECTORY32_V3   IMAGE_LOAD_CONFIG_DIRECTORY32;
     628typedef PIMAGE_LOAD_CONFIG_DIRECTORY32_V3  PIMAGE_LOAD_CONFIG_DIRECTORY32;
     629typedef PCIMAGE_LOAD_CONFIG_DIRECTORY32_V3 PCIMAGE_LOAD_CONFIG_DIRECTORY32;
     630
     631/* No _IMAGE_LOAD_CONFIG_DIRECTORY64_V1 exists. */
     632
     633typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY64_V2
    546634{
    547635    uint32_t  Size;
     
    565653    uint64_t  SEHandlerTable;
    566654    uint64_t  SEHandlerCount;
    567 } IMAGE_LOAD_CONFIG_DIRECTORY64;
    568 typedef IMAGE_LOAD_CONFIG_DIRECTORY64 *PIMAGE_LOAD_CONFIG_DIRECTORY64;
    569 typedef IMAGE_LOAD_CONFIG_DIRECTORY64 const *PCIMAGE_LOAD_CONFIG_DIRECTORY64;
    570 
     655} IMAGE_LOAD_CONFIG_DIRECTORY64_V2;
     656AssertCompileSize(IMAGE_LOAD_CONFIG_DIRECTORY64_V2, 0x70);
     657typedef IMAGE_LOAD_CONFIG_DIRECTORY64_V2 *PIMAGE_LOAD_CONFIG_DIRECTORY64_V2;
     658typedef IMAGE_LOAD_CONFIG_DIRECTORY64_V2 const *PCIMAGE_LOAD_CONFIG_DIRECTORY64_V2;
     659
     660#pragma pack(4) /* Why not 8 byte alignment, baka microsofties?!? */
     661typedef struct _IMAGE_LOAD_CONFIG_DIRECTORY64_V3
     662{
     663    uint32_t  Size;
     664    uint32_t  TimeDateStamp;
     665    uint16_t  MajorVersion;
     666    uint16_t  MinorVersion;
     667    uint32_t  GlobalFlagsClear;
     668    uint32_t  GlobalFlagsSet;
     669    uint32_t  CriticalSectionDefaultTimeout;
     670    uint64_t  DeCommitFreeBlockThreshold;
     671    uint64_t  DeCommitTotalFreeThreshold;
     672    uint64_t  LockPrefixTable;
     673    uint64_t  MaximumAllocationSize;
     674    uint64_t  VirtualMemoryThreshold;
     675    uint64_t  ProcessAffinityMask;
     676    uint32_t  ProcessHeapFlags;
     677    uint16_t  CSDVersion;
     678    uint16_t  Reserved1;
     679    uint64_t  EditList;
     680    uint64_t  SecurityCookie;
     681    uint64_t  SEHandlerTable;
     682    uint64_t  SEHandlerCount;
     683    uint64_t  GuardCFCCheckFunctionPointer;
     684    uint64_t  Reserved2;
     685    uint64_t  GuardCFFunctionTable;
     686    uint64_t  GuardCFFunctionCount;
     687    uint32_t  GuardFlags;
     688} IMAGE_LOAD_CONFIG_DIRECTORY64_V3;
     689#pragma pack()
     690AssertCompileSize(IMAGE_LOAD_CONFIG_DIRECTORY64_V3, 0x94);
     691typedef IMAGE_LOAD_CONFIG_DIRECTORY64_V3 *PIMAGE_LOAD_CONFIG_DIRECTORY64_V3;
     692typedef IMAGE_LOAD_CONFIG_DIRECTORY64_V3 const *PCIMAGE_LOAD_CONFIG_DIRECTORY64_V3;
     693
     694typedef IMAGE_LOAD_CONFIG_DIRECTORY64_V3   IMAGE_LOAD_CONFIG_DIRECTORY64;
     695typedef PIMAGE_LOAD_CONFIG_DIRECTORY64_V3  PIMAGE_LOAD_CONFIG_DIRECTORY64;
     696typedef PCIMAGE_LOAD_CONFIG_DIRECTORY64_V3 PCIMAGE_LOAD_CONFIG_DIRECTORY64;
    571697
    572698typedef struct _IMAGE_DEBUG_DIRECTORY
     
    581707    uint32_t  PointerToRawData;
    582708} IMAGE_DEBUG_DIRECTORY;
     709AssertCompileSize(IMAGE_DEBUG_DIRECTORY, 28);
    583710typedef IMAGE_DEBUG_DIRECTORY *PIMAGE_DEBUG_DIRECTORY;
    584711typedef IMAGE_DEBUG_DIRECTORY const *PCIMAGE_DEBUG_DIRECTORY;
     
    592719    uint8_t    Data[1];
    593720} IMAGE_DEBUG_MISC;
     721AssertCompileSize(IMAGE_DEBUG_MISC, 16);
    594722typedef IMAGE_DEBUG_MISC *PIMAGE_DEBUG_MISC;
    595723typedef IMAGE_DEBUG_MISC const *PCIMAGE_DEBUG_MISC;
     
    603731    uint8_t     bCertificate[8];
    604732} WIN_CERTIFICATE;
     733AssertCompileSize(WIN_CERTIFICATE, 16);
    605734typedef WIN_CERTIFICATE *PWIN_CERTIFICATE;
    606735typedef WIN_CERTIFICATE const *PCWIN_CERTIFICATE;
    607 
    608 
    609 
    610 
    611 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    612 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    613 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    614 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    615 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    616 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    617 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    618 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    619 /* WARNING! NO MORE PRAGMA PACK 4 from here on. Assert size of all new types. */
    620 #pragma pack()
    621 
    622 
    623 
    624736
    625737
  • trunk/src/VBox/Runtime/nt/RTErrConvertFromNtStatus.cpp

    r51530 r51770  
    4949        case STATUS_NO_MORE_FILES:          return VERR_NO_MORE_FILES;
    5050        case STATUS_NO_MORE_ENTRIES:        return VERR_NO_MORE_FILES;
     51        case STATUS_NO_MEMORY:              return VERR_NO_MEMORY;
    5152
    5253        case STATUS_INVALID_HANDLE:         return VERR_INVALID_HANDLE;
     
    6162        case STATUS_OBJECT_PATH_INVALID:    return VERR_INVALID_NAME;
    6263        case STATUS_OBJECT_PATH_NOT_FOUND:  return VERR_PATH_NOT_FOUND;
     64        case STATUS_OBJECT_PATH_SYNTAX_BAD: return VERR_INVALID_NAME;
    6365        case STATUS_BAD_NETWORK_PATH:       return VERR_NET_PATH_NOT_FOUND;
    6466        case STATUS_NOT_A_DIRECTORY:        return VERR_NOT_A_DIRECTORY;
  • trunk/src/VBox/Runtime/r3/posix/process-posix.cpp

    r48935 r51770  
    148148
    149149
     150RTR3DECL(int) RTProcQueryParent(RTPROCESS hProcess, PRTPROCESS phParent)
     151{
     152    if (hProcess == RTProcSelf())
     153    {
     154        *phParent = getppid();
     155        return VINF_SUCCESS;
     156    }
     157    return VERR_NOT_SUPPORTED;
     158}
     159
     160
    150161RTR3DECL(int) RTProcQueryUsername(RTPROCESS hProcess, char *pszUser, size_t cbUser,
    151162                                  size_t *pcbUser)
  • trunk/src/VBox/Runtime/r3/stream.cpp

    r48935 r51770  
    10931093
    10941094/**
     1095 * Dumper vprintf-like function outputting to a stream.
     1096 *
     1097 * @param   pvUser          The stream to print to.  NULL means standard output.
     1098 * @param   pszFormat       Runtime format string.
     1099 * @param   va              Arguments specified by pszFormat.
     1100 */
     1101RTDECL(void) RTStrmDumpPrintfV(void *pvUser, const char *pszFormat, va_list va)
     1102{
     1103    RTStrmPrintfV(pvUser ? (PRTSTREAM)pvUser : g_pStdOut, pszFormat, va);
     1104}
     1105
     1106
     1107/**
    10951108 * Prints a formatted string to the standard output stream (g_pStdOut).
    10961109 *
  • trunk/src/VBox/Runtime/r3/win/ntdll-mini-implib.def

    r49229 r51770  
    55
    66;
    7 ; Copyright (C) 2010-2013 Oracle Corporation
     7; Copyright (C) 2010-2014 Oracle Corporation
    88;
    99; This file is part of VirtualBox Open Source Edition (OSE), as
     
    2727LIBRARY ntdll.dll
    2828EXPORTS
    29     RtlNtStatusToDosError
    30     NtQueryTimerResolution
    31     NtQueryDirectoryFile
    32     NtQueryDirectoryObject
    33     NtQueryInformationFile
    34     NtQueryInformationProcess
    35     NtSetInformationFile
    36     NtSetTimerResolution
    37     NtQueryVolumeInformationFile
    38     NtQueryVirtualMemory
    39     NtCreateFile
    40     NtClose
    41     NtOpenDirectoryObject
    42     NtDeviceIoControlFile
     29  ; Exported name                           - The name x86 name sought by the linker.
     30  ;                                         - This needs to be defined as a symbol, we generate assembly.
     31    NtClose                               ;;= _NtClose@4
     32    NtCreateFile                          ;;= _NtCreateFile@44
     33    NtCreateSection                       ;;= _NtCreateSection@28
     34    NtDelayExecution                      ;;= _NtDelayExecution@8
     35    NtDeviceIoControlFile                 ;;= _NtDeviceIoControlFile@40
     36    NtDuplicateObject                     ;;= _NtDuplicateObject@28
     37    NtOpenDirectoryObject                 ;;= _NtOpenDirectoryObject@12
     38    NtOpenProcess                         ;;= _NtOpenProcess@16
     39    NtOpenProcessToken                    ;;= _NtOpenProcessToken@12
     40    NtOpenThreadToken                     ;;= _NtOpenThreadToken@16
     41    NtQueryDirectoryFile                  ;;= _NtQueryDirectoryFile@44
     42    NtQueryDirectoryObject                ;;= _NtQueryDirectoryObject@28
     43    NtQueryInformationFile                ;;= _NtQueryInformationFile@20
     44    NtQueryInformationProcess             ;;= _NtQueryInformationProcess@20
     45    NtQueryInformationThread              ;;= _NtQueryInformationThread@20
     46    NtQueryInformationToken               ;;= _NtQueryInformationToken@20
     47    NtQueryObject                         ;;= _NtQueryObject@20
     48    NtQueryTimerResolution                ;;= _NtQueryTimerResolution@12
     49    NtQueryVirtualMemory                  ;;= _NtQueryVirtualMemory@24
     50    NtQueryVolumeInformationFile          ;;= _NtQueryVolumeInformationFile@20
     51    NtReadFile                            ;;= _NtReadFile@36
     52    NtReadVirtualMemory                   ;;= _NtReadVirtualMemory@20
     53    NtSetInformationFile                  ;;= _NtSetInformationFile@20
     54    NtSetInformationObject                ;;= _NtSetInformationObject@16
     55    NtSetInformationThread                ;;= _NtSetInformationThread@16
     56    NtSetTimerResolution                  ;;= _NtSetTimerResolution@12
     57    NtWriteFile                           ;;= _NtWriteFile@36
     58    NtWriteVirtualMemory                  ;;= _NtWriteVirtualMemory@20
     59    NtYieldExecution                      ;;= _NtYieldExecution@0
     60                                          ;;
     61    RtlAddAccessAllowedAce                ;;= _RtlAddAccessAllowedAce@16
     62    RtlAddAccessDeniedAce                 ;;= _RtlAddAccessDeniedAce@16
     63    RtlCopySid                            ;;= _RtlCopySid@12
     64    RtlCreateAcl                          ;;= _RtlCreateAcl@12
     65    RtlCreateSecurityDescriptor           ;;= _RtlCreateSecurityDescriptor@8
     66    RtlGetVersion                         ;;= _RtlGetVersion@4
     67    RtlInitializeSid                      ;;= _RtlInitializeSid@12
     68    RtlNtStatusToDosError                 ;;= _RtlNtStatusToDosError@4
     69    RtlSetDaclSecurityDescriptor          ;;= _RtlSetDaclSecurityDescriptor@16
     70    RtlSubAuthoritySid                    ;;= _RtlSubAuthoritySid@8
    4371
  • trunk/src/VBox/Runtime/testcase/Makefile.kmk

    r51165 r51770  
    4949        tstRTBase64 \
    5050        tstRTBitOperations \
     51        tstRTBigNum \
    5152        tstRTCidr \
    5253        tstRTCritSect \
     
    7980        tstLdr \
    8081        tstLdrLoad \
     82        tstRTLdrVerifyPeImage \
    8183        tstRTList \
    8284        tstRTLockValidator \
     
    207209tstRTBase64_SOURCES = tstRTBase64.cpp
    208210
     211tstRTBigNum_TEMPLATE = VBOXR3TSTEXE
     212tstRTBigNum_SOURCES = tstRTBigNum.cpp
     213
    209214tstRTBitOperations_TEMPLATE = VBOXR3TSTEXE
    210215tstRTBitOperations_SOURCES = tstRTBitOperations.cpp
     
    399404tstLdrLoad_SOURCES = tstLdrLoad.cpp
    400405
     406tstRTLdrVerifyPeImage_TEMPLATE = VBOXR3TSTEXE
     407tstRTLdrVerifyPeImage_SOURCES = tstRTLdrVerifyPeImage.cpp
     408
    401409tstRTList_TEMPLATE = VBOXR3TSTEXE
    402410tstRTList_SOURCES = tstRTList.cpp
  • trunk/src/VBox/Runtime/tools/Makefile.kmk

    r51696 r51770  
    55
    66#
    7 # Copyright (C) 2006-2013 Oracle Corporation
     7# Copyright (C) 2006-2014 Oracle Corporation
    88#
    99# This file is part of VirtualBox Open Source Edition (OSE), as
     
    3333bldRTManifest_TEMPLATE = VBoxAdvBldProg
    3434bldRTManifest_SOURCES  = RTManifest.cpp
     35
     36# RTSignTool - Signing utility - build version.  Signed on windows so we can get the certificate from it.
     37BLDPROGS += bldRTSignTool
     38bldRTSignTool_TEMPLATE = VBoxAdvBldProg
     39bldRTSignTool_SOURCES = RTSignTool.cpp
     40bldRTSignTool_DEFS = IPRT_IN_BUILD_TOOL
     41bldRTSignTool_POST_CMDS.win = $(VBOX_SIGN_IMAGE_CMDS)
    3542
    3643ifndef VBOX_ONLY_EXTPACKS_USE_IMPLIBS
     
    8188 RTDbgSymCache_SOURCES = RTDbgSymCache.cpp
    8289
     90 # RTSignTool - Signing utility.
     91 PROGRAMS += RTSignTool
     92 RTSignTool_TEMPLATE = VBoxR3Tool
     93 RTSignTool_SOURCES = RTSignTool.cpp
     94 RTSignTool_LIBS = $(PATH_STAGE_LIB)/SUPR3$(VBOX_SUFF_LIB)
     95
    8396endif # !VBOX_ONLY_EXTPACKS_USE_IMPLIBS
    8497
  • trunk/src/VBox/Runtime/win/RTErrConvertFromWin32.cpp

    r51427 r51770  
    413413        case ERROR_NOT_A_REPARSE_POINT: return VERR_NOT_SYMLINK;
    414414
     415        case NTE_BAD_ALGID:         return VERR_CR_PKIX_UNKNOWN_DIGEST_TYPE;
    415416    }
    416417
  • trunk/src/VBox/Runtime/win/errmsgwin.cpp

    r48935 r51770  
    4444static const RTWINERRMSG  g_aStatusMsgs[] =
    4545{
    46 #include "errmsgcomdata.h"
    47 #if defined(VBOX) && !defined(IN_GUEST)
    48 # include "errmsgvboxcomdata.h"
     46#ifndef IPRT_NO_ERROR_DATA
     47# include "errmsgcomdata.h"
     48# if defined(VBOX) && !defined(IN_GUEST)
     49#  include "errmsgvboxcomdata.h"
     50# endif
     51#else
     52    { "Success.", "ERROR_SUCCESS", 0 },
    4953#endif
    5054    { NULL, NULL, 0 }
     
    7781{
    7882    unsigned i;
    79     for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs); i++)
     83    for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs) - 1U; i++)
    8084        if (g_aStatusMsgs[i].iCode == rc)
    8185            return &g_aStatusMsgs[i];
     
    8690     * actual value in case we pick the wrong entry. Better than always using
    8791     * the "Unknown Status" case. */
    88     for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs); i++)
     92    for (i = 0; i < RT_ELEMENTS(g_aStatusMsgs) - 1U; i++)
    8993        if (g_aStatusMsgs[i].iCode == HRESULT_CODE(rc))
    9094        {
  • trunk/src/bldprogs/bin2c.c

    r48959 r51770  
    5757            "  -width <n>   number of bytes per line (default: 16)\n"
    5858            "  -break <n>   break every <n> lines    (default: -1)\n"
    59             "  -ascii       show ASCII representation of binary as comment\n",
    60             argv0);
     59            "  -ascii       show ASCII representation of binary as comment\n"
     60            "  -export      emit DECLEXPORT\n"
     61            "  --append     append to the output file (default: truncate)\n"
     62            , argv0);
    6163
    6264    return 1;
     
    7274    size_t        uMask = 0;
    7375    int           fAscii = 0;
     76    int           fAppend = 0;
    7477    int           fExport = 0;
    7578    long          iBreakEvery = -1;
     
    105108        }
    106109        else if (!strcmp(argv[iArg], "-ascii"))
    107         {
    108110            fAscii = 1;
    109         }
     111        else if (!strcmp(argv[iArg], "--append"))
     112            fAppend = 1;
    110113        else if (!strcmp(argv[iArg], "-export"))
    111         {
    112114            fExport = 1;
    113         }
    114115        else if (!strcmp(argv[iArg], "-width"))
    115116        {
     
    153154    }
    154155
    155     pFileOut = fopen(argv[iArg+2], "wb");
     156    pFileOut = fopen(argv[iArg+2], fAppend ? "a" : "w"); /* no b! */
    156157    if (!pFileOut)
    157158    {
  • trunk/src/recompiler/Makefile.kmk

    r47423 r51770  
    143143
    144144VBoxRemPrimary_LDFLAGS.solaris = -mimpure-text
    145 VBoxRemPrimary_POST_CMDS       = $(VBOX_SIGN_IMAGE_CMDS)
     145ifdef VBOX_WITH_HARDENING
     146 VBoxRemPrimary_POST_CMDS      = \
     147        $(VBOX_VCC_EDITBIN) /LargeAddressAware /DynamicBase /NxCompat /Release /IntegrityCheck \
     148                /Version:$(VBOX_VERSION_MAJOR)0$(VBOX_VERSION_MINOR).$(VBOX_VERSION_BUILD) "$(out)" \
     149        $$(NLTAB)$(VBOX_SIGN_IMAGE_CMDS)
     150else
     151 VBoxRemPrimary_POST_CMDS      = $(VBOX_SIGN_IMAGE_CMDS)
     152endif
    146153
    147154
  • trunk/tools/bin/gen-slickedit-workspace.sh

    r51348 r51770  
    163163# @param    $1      The output file name base.
    164164# @param    $2      The wildcard spec.
     165# @param    $3      Optional folder override.
    165166my_wildcard()
    166167{
     168    if test -n "$3"; then
     169        MY_FOLDER="$1-$3.lst"
     170    else
     171        MY_FOLDER="$1-All.lst"
     172    fi
    167173    EXCLUDES="*.log;*.kup;*~;*.pyc;*.exe;*.sys;*.dll;*.o;*.obj;*.lib;*.a;*.ko;*.class;*.cvsignore;*.done;*.project;*.actionScriptProperties;*.scm-settings;.svn/*"
    168     echo '        <F N="'"${2}"'/*" Recurse="1" Excludes="'"${EXCLUDES}"'"/>' >> "$1-All.lst"
     174    echo '        <F N="'"${2}"'/*" Recurse="1" Excludes="'"${EXCLUDES}"'"/>' >> "${MY_FOLDER}"
    169175}
    170176
     
    231237                    case "${f}" in
    232238                        ${MY_ROOT_DIR}/include*)
    233                             my_sub_tree "${MY_FILE}" "${f}" "Headers"
     239                            #my_sub_tree "${MY_FILE}" "${f}" "Headers"
     240                            my_wildcard "${MY_FILE}" "${f}" "Headers"
    234241                            ;;
    235242                        *)  my_wildcard "${MY_FILE}" "${f}"
     
    617624#define IEM_MC_ARG(a_Type, a_Name, a_iArg)                 a_Type a_Name
    618625#define IEM_MC_ARG_CONST(a_Type, a_Name, a_Value, a_iArg)  a_Type const a_Name = a_Value
     626
     627#define RTASN1_IMPL_GEN_SEQ_OF_TYPEDEFS_AND_PROTOS(a_SeqOfType, a_ItemType, a_DeclMacro, a_ImplExtNm) typedef struct a_SeqOfType { RTASN1SEQUENCECORE SeqCore; RTASN1ALLOCATION Allocation; uint32_t cItems; RT_CONCAT(P,a_ItemType) paItems; } a_SeqOfType; typedef a_SeqOfType *P##a_SeqOfType, const *PC##a_SeqOfType; int a_ImplExtNm##_DecodeAsn1(struct RTASN1CURSOR *pCursor, uint32_t fFlags, P##a_SeqOfType pThis, const char *pszErrorTag); int a_ImplExtNm##_Compare(PC##a_SeqOfType pLeft, PC##a_SeqOfType pRight)
     628#define RTASN1_IMPL_GEN_SET_OF_TYPEDEFS_AND_PROTOS(a_SetOfType, a_ItemType, a_DeclMacro, a_ImplExtNm) typedef struct a_SetOfType { RTASN1SETCORE SetCore; RTASN1ALLOCATION Allocation; uint32_t cItems; RT_CONCAT(P,a_ItemType) paItems; } a_SetOfType; typedef a_SetOfType *P##a_SetOfType, const *PC##a_SetOfType; int a_ImplExtNm##_DecodeAsn1(struct RTASN1CURSOR *pCursor, uint32_t fFlags, P##a_SetOfType pThis, const char *pszErrorTag); int a_ImplExtNm##_Compare(PC##a_SetOfType pLeft, PC##a_SetOfType pRight)
     629#define RTASN1TYPE_STANDARD_PROTOTYPES_NO_GET_CORE(a_TypeNm, a_DeclMacro, a_ImplExtNm) int  a_ImplExtNm##_Init(P##a_TypeNm pThis, PCRTASN1ALLOCATORVTABLE pAllocator); int  a_ImplExtNm##_Clone(P##a_TypeNm pThis, PC##a_TypeNm) pSrc, PCRTASN1ALLOCATORVTABLE pAllocator); void a_ImplExtNm##_Delete(P##a_TypeNm pThis); int  a_ImplExtNm##_Enum(P##a_TypeNm pThis, PFNRTASN1ENUMCALLBACK pfnCallback, uint32_t uDepth, void *pvUser); int  a_ImplExtNm##_Compare(PC##a_TypeNm) pLeft, PC##a_TypeNm pRight); int  a_ImplExtNm##_DecodeAsn1(PRTASN1CURSOR pCursor, uint32_t fFlags, P##a_TypeNm pThis, const char *pszErrorTag); int  a_ImplExtNm##_CheckSanity(PC##a_TypeNm pThis, uint32_t fFlags, PRTERRINFO pErrInfo, const char *pszErrorTag)
     630#define RTASN1TYPE_STANDARD_PROTOTYPES(a_TypeNm, a_DeclMacro, a_ImplExtNm, a_Asn1CoreNm) inline PRTASN1CORE a_ImplExtNm##_GetAsn1Core(PC##a_TypeNm pThis) { return (PRTASN1CORE)&pThis->a_Asn1CoreNm; } inline bool a_ImplExtNm##_IsPresent(PC##a_TypeNm pThis) { return pThis && RTASN1CORE_IS_PRESENT(&pThis->a_Asn1CoreNm); } RTASN1TYPE_STANDARD_PROTOTYPES_NO_GET_CORE(a_TypeNm, a_DeclMacro, a_ImplExtNm)
     631
    619632EOF
    620633
Note: See TracChangeset for help on using the changeset viewer.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette