Win32 API 日本語リファレンス
ホームSystem.Memory › VirtualProtectFromApp

VirtualProtectFromApp

関数
UWPアプリ向けにコミット済みメモリの保護属性を変更する。
DLLapi-ms-win-core-memory-l1-1-3.dll呼出規約winapiSetLastErrorあり対応OSWindows 10 以降

シグネチャ

// api-ms-win-core-memory-l1-1-3.dll
#include <windows.h>

BOOL VirtualProtectFromApp(
    void* Address,
    UINT_PTR Size,
    DWORD NewProtection,
    DWORD* OldProtection
);

パラメーター

名前方向説明
Addressvoid*in

アクセス保護属性を変更するページ領域の先頭ページを示すアドレスへのポインターです。

指定する領域内のすべてのページは、VirtualAllocVirtualAllocFromApp、または VirtualAllocEx 関数を MEM_RESERVE を指定して呼び出した際に確保された、同一の予約領域内に存在している必要があります。これらのページは、VirtualAllocVirtualAllocFromApp、または VirtualAllocEx への個別の呼び出しによって MEM_RESERVE を指定して確保された、隣接する予約領域にまたがることはできません。

SizeUINT_PTRinアクセス保護属性を変更する領域のサイズ(バイト単位)です。影響を受けるページ領域には、Address パラメーターから (Address+Size) までの範囲に含まれる 1 バイト以上を持つすべてのページが含まれます。つまり、ページ境界をまたぐ 2 バイトの範囲を指定すると、両方のページの保護属性が変更されます。
NewProtectionDWORDin

メモリ保護オプションです。このパラメーターには、 メモリ保護定数のいずれかを指定できます。

マップされたビューの場合、この値は、ビューをマップした際に指定したアクセス保護と互換性がある必要があります(MapViewOfFileMapViewOfFileEx、および MapViewOfFileExNuma を参照してください)。

次の定数を指定するとエラーになります。

次の定数は、codeGeneration 機能を持つアプリでのみ許可されます。
OldProtectionDWORD*out指定したページ領域の先頭ページの、以前のアクセス保護値を受け取る変数へのポインターです。このパラメーターが NULL である場合、または有効な変数を指していない場合、関数は失敗します。

戻り値の型: BOOL

公式ドキュメント

呼び出し元プロセスの仮想アドレス空間において、コミット済みページ領域の保護属性を変更します。(VirtualProtectFromApp)

戻り値

関数が成功すると、戻り値は 0 以外になります。

関数が失敗すると、戻り値は 0 になります。拡張エラー情報を取得するには、 GetLastError を呼び出してください。

解説(Remarks)

ジャストインタイム(JIT)機能を備えた Windows ストアアプリから VirtualProtectFromApp を呼び出すことで、JIT 機能を利用できます。JIT 機能を使用するには、アプリのマニフェストファイルに codeGeneration 機能を含める必要があります。

アクセス保護値を設定できるのは、コミット済みのページに対してのみです。指定した領域内のいずれかのページがコミットされていない状態の場合、関数は失敗し、指定領域内のどのページのアクセス保護も変更せずに復帰します。

PAGE_GUARD 保護修飾子は、ガードページを設定します。ガードページは、一度限りのアクセスアラームとして機能します。詳細については、 ガードページの作成を参照してください。

GlobalAllocHeapAlloc、または LocalAlloc によって割り当てられたメモリブロックのページ保護を VirtualProtectFromApp で変更することは避けるのが望ましいです。1 つのページ上に複数のメモリブロックが存在する場合があるためです。ヒープマネージャーは、ヒープ内のすべてのページが少なくとも読み取りおよび書き込みのアクセスを許可していることを前提としています。

VirtualProtectFromApp ではページを実行可能としてマークできますが、書き込み権限と実行権限を同時に設定することはできません。

実行可能になる領域を保護する場合、コードを配置した後に FlushInstructionCache を適切に呼び出してキャッシュの一貫性を確保する責任は、呼び出し元のプログラムにあります。そうしないと、新たに実行可能になった領域のコードを実行しようとした際に、予期しない結果が生じる可能性があります。

出典・ライセンス: 上記「公式ドキュメント」の内容は Microsoft の Win32 API ドキュメント(MicrosoftDocs/sdk-api)を日本語に翻訳・改変したものです。© Microsoft Corporation. CC BY 4.0 で提供。
Microsoft 公式リファレンス: 英語 (en-us) · 日本語 (ja-jp) · 原文ソース (GitHub)

各言語での呼び出し定義

// api-ms-win-core-memory-l1-1-3.dll
#include <windows.h>

BOOL VirtualProtectFromApp(
    void* Address,
    UINT_PTR Size,
    DWORD NewProtection,
    DWORD* OldProtection
);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("api-ms-win-core-memory-l1-1-3.dll", SetLastError = true, ExactSpelling = true)]
static extern bool VirtualProtectFromApp(
    IntPtr Address,   // void*
    UIntPtr Size,   // UINT_PTR
    uint NewProtection,   // DWORD
    out uint OldProtection   // DWORD* out
);
<DllImport("api-ms-win-core-memory-l1-1-3.dll", SetLastError:=True, ExactSpelling:=True)>
Public Shared Function VirtualProtectFromApp(
    Address As IntPtr,   ' void*
    Size As UIntPtr,   ' UINT_PTR
    NewProtection As UInteger,   ' DWORD
    <Out> ByRef OldProtection As UInteger   ' DWORD* out
) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
' Address : void*
' Size : UINT_PTR
' NewProtection : DWORD
' OldProtection : DWORD* out
Declare PtrSafe Function VirtualProtectFromApp Lib "api-ms-win-core-memory-l1-1-3" ( _
    ByVal Address As LongPtr, _
    ByVal Size As LongPtr, _
    ByVal NewProtection As Long, _
    ByRef OldProtection As Long) As Long
' VBA7前提(PtrSafe)。32bit Office では LongPtr→Long。Integer=16bit / Long=32bit / LongLong=64bit。
import ctypes
from ctypes import wintypes

VirtualProtectFromApp = ctypes.windll.LoadLibrary("api-ms-win-core-memory-l1-1-3.dll").VirtualProtectFromApp
VirtualProtectFromApp.restype = wintypes.BOOL
VirtualProtectFromApp.argtypes = [
    ctypes.POINTER(None),  # Address : void*
    ctypes.c_size_t,  # Size : UINT_PTR
    wintypes.DWORD,  # NewProtection : DWORD
    ctypes.POINTER(wintypes.DWORD),  # OldProtection : DWORD* out
]
# GetLastError: use ctypes.GetLastError() (or ctypes.WinDLL(use_last_error=True))
require 'fiddle'
require 'fiddle/import'

lib = Fiddle.dlopen('api-ms-win-core-memory-l1-1-3.dll')
VirtualProtectFromApp = Fiddle::Function.new(
  lib['VirtualProtectFromApp'],
  [
    Fiddle::TYPE_VOIDP,  # Address : void*
    Fiddle::TYPE_UINTPTR_T,  # Size : UINT_PTR
    -Fiddle::TYPE_INT,  # NewProtection : DWORD
    Fiddle::TYPE_VOIDP,  # OldProtection : DWORD* out
  ],
  Fiddle::TYPE_INT)
#[link(name = "api-ms-win-core-memory-l1-1-3")]
extern "system" {
    fn VirtualProtectFromApp(
        Address: *mut (),  // void*
        Size: usize,  // UINT_PTR
        NewProtection: u32,  // DWORD
        OldProtection: *mut u32  // DWORD* out
    ) -> i32;
}
// crates: windows-sys provides ready-made bindings for this API.
$sig = @"
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("api-ms-win-core-memory-l1-1-3.dll", SetLastError = true)]
public static extern bool VirtualProtectFromApp(IntPtr Address, UIntPtr Size, uint NewProtection, out uint OldProtection);
"@
$api = Add-Type -MemberDefinition $sig -Name 'api-ms-win-core-memory-l1-1-3_VirtualProtectFromApp' -Namespace Win32 -PassThru
# $api::VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
#uselib "api-ms-win-core-memory-l1-1-3.dll"
#func global VirtualProtectFromApp "VirtualProtectFromApp" sptr, sptr, sptr, sptr
; VirtualProtectFromApp Address, Size, NewProtection, varptr(OldProtection)   ; 戻り値は stat
; Address : void* -> "sptr"
; Size : UINT_PTR -> "sptr"
; NewProtection : DWORD -> "sptr"
; OldProtection : DWORD* out -> "sptr"
; ※HSP3.7は #func のため戻り値はシステム変数 stat に格納されます。
出力引数:
#uselib "api-ms-win-core-memory-l1-1-3.dll"
#cfunc global VirtualProtectFromApp "VirtualProtectFromApp" sptr, sptr, int, var
; res = VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
; Address : void* -> "sptr"
; Size : UINT_PTR -> "sptr"
; NewProtection : DWORD -> "int"
; OldProtection : DWORD* out -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
出力引数:
; BOOL VirtualProtectFromApp(void* Address, UINT_PTR Size, DWORD NewProtection, DWORD* OldProtection)
#uselib "api-ms-win-core-memory-l1-1-3.dll"
#cfunc global VirtualProtectFromApp "VirtualProtectFromApp" intptr, intptr, int, var
; res = VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
; Address : void* -> "intptr"
; Size : UINT_PTR -> "intptr"
; NewProtection : DWORD -> "int"
; OldProtection : DWORD* out -> "var"
; ※出力/バッファ引数は var 方式(変数を直接渡す)。varptr 方式にも切替可。
import (
	"golang.org/x/sys/windows"
	"unsafe"
)

var (
	api_ms_win_core_memory_l1_1_3 = windows.NewLazySystemDLL("api-ms-win-core-memory-l1-1-3.dll")
	procVirtualProtectFromApp = api_ms_win_core_memory_l1_1_3.NewProc("VirtualProtectFromApp")
)

// Address (void*), Size (UINT_PTR), NewProtection (DWORD), OldProtection (DWORD* out)
r1, _, err := procVirtualProtectFromApp.Call(
	uintptr(Address),
	uintptr(Size),
	uintptr(NewProtection),
	uintptr(OldProtection),
)
_ = err  // syscall.Errno (valid when the call sets last-error)
_ = r1   // BOOL
function VirtualProtectFromApp(
  Address: Pointer;   // void*
  Size: NativeUInt;   // UINT_PTR
  NewProtection: DWORD;   // DWORD
  OldProtection: Pointer   // DWORD* out
): BOOL; stdcall;
  external 'api-ms-win-core-memory-l1-1-3.dll' name 'VirtualProtectFromApp';
result := DllCall("api-ms-win-core-memory-l1-1-3\VirtualProtectFromApp"
    , "Ptr", Address   ; void*
    , "UPtr", Size   ; UINT_PTR
    , "UInt", NewProtection   ; DWORD
    , "Ptr", OldProtection   ; DWORD* out
    , "Int")   ; return: BOOL
●VirtualProtectFromApp(Address, Size, NewProtection, OldProtection) = DLL("api-ms-win-core-memory-l1-1-3.dll", "bool VirtualProtectFromApp(void*, int, dword, void*)")
# 呼び出し: VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
# Address : void* -> "void*"
# Size : UINT_PTR -> "int"
# NewProtection : DWORD -> "dword"
# OldProtection : DWORD* out -> "void*"
# なでしこ1は32bit・ANSI(Shift_JIS)。文字列=char*(ANSI)、ポインタ/ハンドル=void*(4byte)。
const std = @import("std");

extern "api-ms-win-core-memory-l1-1-3" fn VirtualProtectFromApp(
    Address: ?*anyopaque, // void*
    Size: usize, // UINT_PTR
    NewProtection: u32, // DWORD
    OldProtection: [*c]u32 // DWORD* out
) callconv(std.os.windows.WINAPI) i32;
proc VirtualProtectFromApp(
    Address: pointer,  # void*
    Size: uint,  # UINT_PTR
    NewProtection: uint32,  # DWORD
    OldProtection: ptr uint32  # DWORD* out
): int32 {.importc: "VirtualProtectFromApp", stdcall, dynlib: "api-ms-win-core-memory-l1-1-3.dll".}
pragma(lib, "api-ms-win-core-memory-l1-1-3");
extern(Windows)
int VirtualProtectFromApp(
    void* Address,   // void*
    size_t Size,   // UINT_PTR
    uint NewProtection,   // DWORD
    uint* OldProtection   // DWORD* out
);
ccall((:VirtualProtectFromApp, "api-ms-win-core-memory-l1-1-3.dll"), stdcall, Int32,
      (Ptr{Cvoid}, Csize_t, UInt32, Ptr{UInt32}),
      Address, Size, NewProtection, OldProtection)
# Address : void* -> Ptr{Cvoid}
# Size : UINT_PTR -> Csize_t
# NewProtection : DWORD -> UInt32
# OldProtection : DWORD* out -> Ptr{UInt32}
# stdcall は 32bit のみ意味を持つ(x64 では無視)。
local ffi = require("ffi")
ffi.cdef[[
int32_t VirtualProtectFromApp(
    void* Address,
    uintptr_t Size,
    uint32_t NewProtection,
    uint32_t* OldProtection);
]]
local api-ms-win-core-memory-l1-1-3 = ffi.load("api-ms-win-core-memory-l1-1-3")
-- api-ms-win-core-memory-l1-1-3.VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
-- Address : void*
-- Size : UINT_PTR
-- NewProtection : DWORD
-- OldProtection : DWORD* out
-- 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
const koffi = require('koffi');
const lib = koffi.load('api-ms-win-core-memory-l1-1-3.dll');
const VirtualProtectFromApp = lib.func('__stdcall', 'VirtualProtectFromApp', 'int32_t', ['void *', 'uintptr_t', 'uint32_t', 'uint32_t *']);
// VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
// Address : void* -> 'void *'
// Size : UINT_PTR -> 'uintptr_t'
// NewProtection : DWORD -> 'uint32_t'
// OldProtection : DWORD* out -> 'uint32_t *'
// 出力ポインタは koffi.out(...) で包む。構造体は koffi.struct で定義。
const lib = Deno.dlopen("api-ms-win-core-memory-l1-1-3.dll", {
  VirtualProtectFromApp: { parameters: ["pointer", "usize", "u32", "pointer"], result: "i32" },
});
// lib.symbols.VirtualProtectFromApp(Address, Size, NewProtection, OldProtection)
// Address : void* -> "pointer"
// Size : UINT_PTR -> "usize"
// NewProtection : DWORD -> "u32"
// OldProtection : DWORD* out -> "pointer"
// 文字列引数は "buffer"(NUL 終端のバイト列を Uint8Array で渡す)。
// 値渡し構造体は { struct: [ ...field types... ] } を使用。
<?php
$ffi = FFI::cdef(<<<C
int32_t VirtualProtectFromApp(
    void* Address,
    size_t Size,
    uint32_t NewProtection,
    uint32_t* OldProtection);
C, "api-ms-win-core-memory-l1-1-3.dll");
// $ffi->VirtualProtectFromApp(Address, Size, NewProtection, OldProtection);
// Address : void*
// Size : UINT_PTR
// NewProtection : DWORD
// OldProtection : DWORD* out
// 構造体/GUIDへのポインタは cdef が通るよう void* で表記(実型は各引数コメント参照)。値渡し構造体・enum は対応する typedef を cdef に追加すること。
// WINAPI(stdcall): x64 では呼出規約が統一されるため問題なし。x86 では __stdcall 対応のラッパが必要な場合あり。
import com.sun.jna.*;
import com.sun.jna.ptr.*;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.win32.W32APIOptions;

public interface Api-ms-win-core-memory-l1-1-3 extends StdCallLibrary {
    Api-ms-win-core-memory-l1-1-3 INSTANCE = Native.load("api-ms-win-core-memory-l1-1-3", Api-ms-win-core-memory-l1-1-3.class);
    boolean VirtualProtectFromApp(
        Pointer Address,   // void*
        long Size,   // UINT_PTR
        int NewProtection,   // DWORD
        IntByReference OldProtection   // DWORD* out
    );
}
@[Link("api-ms-win-core-memory-l1-1-3")]
lib Libapi-ms-win-core-memory-l1-1-3
  fun VirtualProtectFromApp = VirtualProtectFromApp(
    Address : Void*,   # void*
    Size : LibC::SizeT,   # UINT_PTR
    NewProtection : UInt32,   # DWORD
    OldProtection : UInt32*   # DWORD* out
  ) : Int32
end
# 構造体/GUID/enum は lib 内に対応する型定義が必要。
# 呼出規約: x64 は規約統一のため OK。x86(32bit)は WINAPI=stdcall だが Crystal の fun に stdcall 付与構文がなく非対応。
import 'dart:ffi';
import 'package:ffi/ffi.dart';

typedef VirtualProtectFromAppNative = Int32 Function(Pointer<Void>, UintPtr, Uint32, Pointer<Uint32>);
typedef VirtualProtectFromAppDart = int Function(Pointer<Void>, int, int, Pointer<Uint32>);
final VirtualProtectFromApp = DynamicLibrary.open('api-ms-win-core-memory-l1-1-3.dll')
    .lookupFunction<VirtualProtectFromAppNative, VirtualProtectFromAppDart>('VirtualProtectFromApp');
// Address : void* -> Pointer<Void>
// Size : UINT_PTR -> UintPtr
// NewProtection : DWORD -> Uint32
// OldProtection : DWORD* out -> Pointer<Uint32>
// 文字列は package:ffi の "...".toNativeUtf16()/toNativeUtf8() で変換。
{$mode objfpc}{$H+}
function VirtualProtectFromApp(
  Address: Pointer;   // void*
  Size: NativeUInt;   // UINT_PTR
  NewProtection: DWORD;   // DWORD
  OldProtection: Pointer   // DWORD* out
): BOOL; stdcall;
  external 'api-ms-win-core-memory-l1-1-3.dll' name 'VirtualProtectFromApp';
import Foreign
import Foreign.C.Types
import Foreign.C.String

foreign import stdcall safe "VirtualProtectFromApp"
  c_VirtualProtectFromApp :: Ptr () -> CUIntPtr -> Word32 -> Ptr Word32 -> IO CInt
-- Address : void* -> Ptr ()
-- Size : UINT_PTR -> CUIntPtr
-- NewProtection : DWORD -> Word32
-- OldProtection : DWORD* out -> Ptr Word32
-- 要 GHC(Windows)。stdcall は x64 では ccall として扱われる。ブロックする API は safe 呼び出し推奨。
open Ctypes
open Foreign

let virtualprotectfromapp =
  foreign "VirtualProtectFromApp"
    ((ptr void) @-> size_t @-> uint32_t @-> (ptr uint32_t) @-> returning int32_t)
(* Address : void* -> (ptr void) *)
(* Size : UINT_PTR -> size_t *)
(* NewProtection : DWORD -> uint32_t *)
(* OldProtection : DWORD* out -> (ptr uint32_t) *)
(* foreign は cdecl 前提。x64 Windows では WINAPI と一致。構造体は ctypes structure を定義のこと。 *)
(cffi:define-foreign-library api-ms-win-core-memory-l1-1-3 (t "api-ms-win-core-memory-l1-1-3.dll"))
(cffi:use-foreign-library api-ms-win-core-memory-l1-1-3)

(cffi:defcfun ("VirtualProtectFromApp" virtual-protect-from-app :convention :stdcall) :int32
  (address :pointer)   ; void*
  (size :uint64)   ; UINT_PTR
  (new-protection :uint32)   ; DWORD
  (old-protection :pointer))   ; DWORD* out
; isize/usize(INT_PTR/SIZE_T)は x64 前提で :int64/:uint64。x86 では :int32/:uint32。
use Win32::API;
my $VirtualProtectFromApp = Win32::API::More->new('api-ms-win-core-memory-l1-1-3',
    'BOOL VirtualProtectFromApp(LPVOID Address, WPARAM Size, DWORD NewProtection, LPVOID OldProtection)');
# my $ret = $VirtualProtectFromApp->Call($Address, $Size, $NewProtection, $OldProtection);
# Address : void* -> LPVOID
# Size : UINT_PTR -> WPARAM
# NewProtection : DWORD -> DWORD
# OldProtection : DWORD* out -> LPVOID
# 値渡し構造体は pack() した文字列、または Win32::API::Struct を使用。

関連項目

公式の関連項目