juntalis
juntalis
Reputation Top 1%
Charles Grunwald
11 Snippets  (87th place)
Published
1 Channel
Created
5 Channels
Following
264 points  (116th place)
Reputation
Junior Code Generator
Serious Code Generator
Junior Publisher
Junior Trend Maker
Junior Popular Coder
Serious Popular Coder
Junior Autobiographer
Serious Autobiographer
Senior Autobiographer
Master Autobiographer
Junior Snip2Coder
Junior Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by juntalis

public by juntalis  1631  9  5  0

Common-use functions for batch

A collection of utility functions for use in Windows batch scripts. Functions near the bottom may or may not cleanly work in all situations. Still need to work the kinks out of them.
@echo off

:dirname
rem Given a filepath, resolve the absolute filepath of its parents folder.
rem \param [out] %1 - The variable name to output the results to.
rem \param [in]  %2 - The filepath that we'll be operating on.
call set "%~1=%%~dp2"
call set "%~1=%%%~1:~0,-1%%"
goto :EOF

:filename
rem Given a filepath, extract the filename. (name and file extension)
rem \param [out] %1 - The variable name to output the results to.
rem \param [in]  %2 - The filepath that we'll be operating on.
call set "%~1=%~nx2"
goto :EOF

:basename
rem Given a filepath, extract the basename. (name without file extension)
rem \param [out] %1 - The variable name to output the results to.
rem \param [in]  %2 - The filepath that we'll be operating on.
call set "%~1=%~n2"
goto :EOF

:abspath
rem Resolve the absolute filepath to a file or folder.
rem \param [out] %1 - The variable name to output the results to.
rem \param [in]  %2 - The filepath that we'll be operating on.
call set "%~1=%~f2"
goto :EOF

:which
rem Get the path of the program in arg 2 and set the variable who's
rem name was specified in the first argument.
rem \param [out] %1 - The variable name to output the executable path to.
rem \param [in]  %2 - The executable name to search for.
call set "%~1=%~f$PATH:2"
goto :EOF

:trimslashes
rem Trims all trailing '/' and '\')from a variable.
rem \param [inout] %1 - The name of the variable we'll be operating on.
call set "__C=%%%~1:~-1%%"
if not "%__C%x"=="\x" if not "%__C%x"=="/x" (set "__C=" & goto :EOF)
call set "%~1=%%%~1:~0,-1%%"
goto trimslashes

:strlen
rem Determine the length of the string specified in the second argument.
rem \param [out] %1 - The variable name to output the results to.
rem \param [in]  %2 - The subject text that we will be measuring.
setlocal
set _STRLEN_BUFFER_=%~2
set /A _STRLEN_LENGTH_=0
:strlen_loop
if "%_STRLEN_BUFFER_%x"=="x" goto strlen_continue
set _STRLEN_CHAR_=%_STRLEN_BUFFER_:~0,1%
set /A _STRLEN_LENGTH_ += 1
set _STRLEN_BUFFER_=%_STRLEN_BUFFER_:~1%
goto strlen_loop
:strlen_continue
endlocal & call set %~1=%_STRLEN_LENGTH_%
goto :EOF

:rreplace
rem Replaces recursively.
rem \param [out] %1 - The variable name to output the results to.
rem \param [in]  %2 - The subject text to search and replace through.
rem \param [in]  %3 - The substring to search for in %2.
rem \param [in]  %4 - The replacement text to substitute when %3 is found.
call set "%~1=%~2"
verify>nul
:rreplace_work
(call echo %%%~1%%|find "%~3")>nul 2>nul
if errorlevel 1 goto rreplace_done
verify>nul
call set "%~1=%%%~1:%~3=%~4%%"
goto rreplace_work
:rreplace_done
verify>nul
goto :EOF

:tolower
rem Subroutine to convert a variable VALUE to all lower case.
rem The argument for this subroutine is the variable NAME.
for %%C in ("A=a" "B=b" "C=c" "D=d" "E=e" "F=f" "G=g" "H=h" "I=i" "J=j" "K=k" "L=l" "M=m" "N=n" "O=o" "P=p" "Q=q" "R=r" "S=s" "T=t" "U=u" "V=v" "W=w" "X=x" "Y=y" "Z=z") do @call set "%~1=%%%~1:%%~C%%"
goto :EOF

:isdefined
rem Checks if a variable has a defined value.
if "%~1x"=="x" exit /B 1
if not defined %~1 exit /B 1
goto :EOF

:splitenv
rem Given an expandable environment variable such as PATH or PATHEXT,
rem split the variable into its individual lowercase components such that the
rem value of:
rem   .COM;.BAT;.EXE
rem would expand into:
rem   ".COM" ".BAT" ".EXE"
rem The resulting value should be suitable for using with the FOR command.
call set %~1=%%%~2:;=" "%%
call set %~1="%%%~1%%"
call :tolower "%~1"
goto :EOF

:whichex
rem Similar to the original which above, but with additional functionality
rem to use the PATHEXT variable when the executable is specified without a
rem file extension. (ex: Specifying cmd.exe as cmd)
rem \param [out] %1 - The variable name to output the executable path to.
rem \param [in]  %2 - The executable name to search for.
setlocal
set _WHICHEX_TARGET_=%~2
call :which _WHICHEX_RESULT_ "%_WHICHEX_TARGET_%"
if exist "%_WHICHEX_RESULT_%" goto whichex_success
if not "%~x2x"=="x" goto whichex_failure
goto whichex_pathext
:whichex_testpath
rem Given a file basename and extension, see if we can find a matching
rem executable on the system PATH.
if errorlevel 1 exit /B %ERRORLEVEL%
call :which _WHICHEX_RESULT_ "%~1%~2"
if exist "%_WHICHEX_RESULT_%" exit /B 1
goto :EOF
:whichex_pathext
rem No file extension was found on our executable name. First we'll try
rem a search with no extension, (as it was specified) and if that fails,
rem we'll try the search again with each file extension in PATHEXT until
rem we find a match. (or run out of extensions)
call :splitenv _WHICHEX_PATHEXT_ PATHEXT
for %%E in (%_WHICHEX_PATHEXT_%) do @call :whichex_testpath "%~nx2" "%%~E"
rem When an executable is found, the errorcode is set to 1 to indicate success.
if errorlevel 1 goto whichex_success
rem If it's still zero at this point, that means we failed to find our executable.
goto whichex_failure
:whichex_success
rem We maanged to resolve the executable path, which is now stored in a
rem localized variable named _WHICHEX_RESULT_. Copy that value over to
rem our outgoing parameter and cleanup.
verify>nul
call set _WHICHEX_COPYCMD_=set "%~1=%_WHICHEX_RESULT_%"
endlocal & call %_WHICHEX_COPYCMD_%
goto :EOF
:whichex_failure
rem We failed to find the executable path based on the info given. Clean
rem up and report the error.
set _WHICHEX_RESULT_=
endlocal
call set %~1=%_WHICHEX_RESULT_%
exit /B 1


                        
;

public by juntalis  639  0  3  0

Extensions to the JSOM client context classes for accessing their cached SP.FormDigestInfo instances.

Extensions to the JSOM client context classes for accessing their cached SP.FormDigestInfo instances.: SP.FormDigestInfo.js
// Should probably only be used if you're using JSOM from somewhere without
// a __REQUESTDIGEST value or if you need more than just the digest value.
// To avoid having to make this asynchronous and deal with callbacks, this
// code assumes that you've run executeQueryAsync at least once with form
// digest handling enabled. (Default behavior - I think - but you can
// use get/set_formDigestHandlingEnabled if I'm wrong)
//
// Example:
// 
//     var ctx = SP.ClientContext.get_current();
//     ctx.executeQueryAsync(function(){
//         var formDigest = ctx.get_formDigestInfo();
//         console.log(formDigest.get_digestValue());
//     }, function(){ throw new Error('executeQueryAsync failed!'); });
//
// See the bottom of the file for info on the SP.FormDigestInfo class.

(function() {
    // Cached member name for the FormDigestInfo cache.
    var fdiCacheKey = null;
    
    /**
     * Grabs the cached SP.FormDigestInfo for a context. The first call will
     * attempt to resolve the member name used for the digest cache, throwing
     * an exception if that attempt fails.
     * @private
     * @param {(SP.ClientRuntimeContext|SP.ClientContext)} clientContext - subject
     * @returns {SP.FormDigestInfo}
     */
    function getCachedFormDigestInfo(clientContext) {
        // Grab the API url used to lookup our form digest instance.
        var apiUrl = clientContext.get_contextInfoUrl();
        
        // Attempt to resolve the cache member name if necessary
        if(fdiCacheKey === null) {
            for(var key in SP.ClientRuntimeContext) {
                var member = SP.ClientRuntimeContext[key];
                if(typeof(member) === 'object' &&
                  (member[apiUrl] instanceof SP.FormDigestInfo)) {
                    fdiCacheKey = key;
                    break;
                }
            }
            
            // verify the success of the attempt
            if(fdiCacheKey === null) {
                throw new Error('Failed to resolve the digest cache member ' +
                                'name. (Verify that executeQueryAsync was ' +
                                'called)')
            }
        }
        
        // Return the cached instance.
        return SP.ClientRuntimeContext[fdiCacheKey][apiUrl];
    }
    
    /**
     * Get the API url used for requesting context info. (Deobfuscated from
     * SP.ClientRuntimeContext.prototype.$2c_0)
     * @returns {string}
     */
    SP.ClientRuntimeContext.prototype.get_contextInfoUrl = function SP_ClientRuntimeContext$get_contextInfoUrl() {
        var webUrl = this.get_url();
        if(!webUrl.endsWith('/')) {
            webUrl += '/';
        }
        webUrl += '_api/contextinfo';
        return this.getRequestUrl(webUrl);
    };
    
    /**
     * Get the current cached form digest info instance for this context.
     * Note: Must call executeQueryAsync at least once with form digest
     * handling enabled. Failure to do so will result in an exception being
     * thrown.
     * @returns {SP.FormDigestInfo}
     */
    SP.ClientRuntimeContext.prototype.get_formDigestInfo = function SP_ClientRuntimeContext$get_formDigestInfo() {
        return getCachedFormDigestInfo(this);
    };
    
    // If SP.js has already been loaded, we'll need to manually copy over
    // the prototype extensions to the SP.ClientContext class.
    if(typeof(SP.ClientContext) !== 'undefined') {
        SP.ClientContext.prototype.get_contextInfoUrl = SP.ClientRuntimeContext.prototype.get_contextInfoUrl;
        SP.ClientContext.prototype.get_formDigestInfo = SP.ClientRuntimeContext.prototype.get_formDigestInfo;
    }
})();

// SP.FormDigestInfo Info:
// For some reason, SP.FormDigestInfo is only documented in some of the
// non-English versions of MSDN. The original English documentation that's
// missing from the main MSDN is included:
//
// https://msdn.microsoft.com/pt-br/library/office/dn754011.aspx
// 
// Note: The examples in the documentation are actually wrong and would throw
// an error if run. (They treat SP.FormDigestInfo like a singleton instance
// instead of the class that it is)
// 
// In case that documentation is removed at some point, the class just has
// few public members:
//
// new SP.FormDigestInfo() 
//
// string SP.FormDigestInfo.prototype.get_digestValue()
// string SP.FormDigestInfo.prototype.set_digestValue(string value)
//
// Date SP.FormDigestInfo.prototype.get_expiration()
// Date SP.FormDigestInfo.prototype.set_expiration(Date expiration)
//
// string SP.FormDigestInfo.prototype.get_webServerRelativeUrl()
// string SP.FormDigestInfo.prototype.set_webServerRelativeUrl(string value)
//


;

public by juntalis  3819  8  6  0

Reimplementation of rmtree supporting Windows reparse points

Ctypes-based implementation of shutil.rmtree that correctly handles Windows reparse point folders. (symbolic links, junctions, etc) As of Python 2.7.5, the builtin shutil.rmtree does not detect the presence of reparse points. (junctions and symbolic links) As a result, any reparse point folder found during the execution of shutil.rmtree is itera
#!python.exe
# encoding: utf-8
from __future__ import with_statement
import os, ctypes, sys
from ctypes.wintypes import DWORD, INT, LPWSTR, LONG, WORD, BYTE, WCHAR

# Some utility wrappers for pointer stuff. 
class c_void(ctypes.Structure):
    # c_void_p is a buggy return type, converting to int, so
    # POINTER(None) == c_void_p is actually written as
    # POINTER(c_void), so it can be treated as a real pointer.
    _fields_ = [('dummy', ctypes.c_int)]

    def __init__(self, value=None):
        if value is None: value = 0
        super(c_void, self).__init__(value)

def POINTER(obj):
    ptr = ctypes.POINTER(obj)
    # Convert None to a real NULL pointer to work around bugs
    # in how ctypes handles None on 64-bit platforms
    if not isinstance(ptr.from_param, classmethod):
        def from_param(cls, x):
            if x is None: return cls()
            return x

        ptr.from_param = classmethod(from_param)
    return ptr

# Shadow built-in c_void_p
LPVOID = c_void_p = POINTER(c_void)

# Globals
NULL = LPVOID(0)
kernel32 = ctypes.WinDLL('kernel32')
advapi32 = ctypes.WinDLL('advapi32')
_obtained_privileges = []

# Aliases to functions/classes, and utility lambdas
cast = ctypes.cast
byref = ctypes.byref
sizeof = ctypes.sizeof
WinError = ctypes.WinError
hasflag = lambda value, flag: (value & flag) == flag

# Constants derived from C
INVALID_HANDLE_VALUE = -1

# Desired access for OpenProcessToken
TOKEN_ADJUST_PRIVILEGES = 0x0020

# SE Privilege Names
SE_RESTORE_NAME = 'SeRestorePrivilege'
SE_BACKUP_NAME = 'SeBackupPrivilege'

# SE Privilege Attributes
SE_PRIVILEGE_ENABLED = 0x00000002L

# Access
FILE_ANY_ACCESS = 0

# CreateFile flags
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000

# Generic access
GENERIC_READ = 0x80000000L
GENERIC_WRITE = 0x40000000L
GENERIC_RW = GENERIC_READ | GENERIC_WRITE

# File shared access
FILE_SHARE_READ = 0x00000001
FILE_SHARE_WRITE = 0x00000002
FILE_SHARE_DELETE = 0x00000004
FILE_SHARE_ALL = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE

# File stuff
OPEN_EXISTING = 3
FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
FILE_DEVICE_FILE_SYSTEM = 0x00000009

# Utility lambdas for figuring out ctl codes
CTL_CODE = lambda devtype, func, meth, acc: (devtype << 16) | (acc << 14) | (func << 2) | meth

# Methods
METHOD_BUFFERED = 0

# WinIoCtl Codes
FSCTL_GET_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED, FILE_ANY_ACCESS)
FSCTL_DELETE_REPARSE_POINT = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 43, METHOD_BUFFERED, FILE_ANY_ACCESS)

# Reparse Point buffer constants
MAX_NAME_LENGTH = 1024
MAX_REPARSE_BUFFER = 16 * MAX_NAME_LENGTH
REPARSE_GUID_DATA_BUFFER_HEADER_SIZE = (2 * sizeof(WORD)) + (sizeof(DWORD) * 5)

# For our generic reparse buffer
MAX_GENERIC_REPARSE_BUFFER = MAX_REPARSE_BUFFER - REPARSE_GUID_DATA_BUFFER_HEADER_SIZE

# Type aliases
UCHAR = ctypes.c_ubyte
ULONG_PTR = ctypes.c_ssize_t
LPDWORD = POINTER(DWORD)

# CTypes-based wrapper classes
class BOOL(INT):
    """
    Wrapper around ctypes.wintypes.INT (ctypes.c_int) to make BOOL act a bit more like
    a boolean.
    """

    @classmethod
    def from_param(cls, value):
        if isinstance(value, ctypes._SimpleCData):
            return BOOL(value.value)
        elif not value or value is None:
            return BOOL(0)
        else:
            raise TypeError('Dont know what to do with instance of {0}'.format(type(value)))

    def __eq__(self, other):
        value = bool(self.value)
        if isinstance(other, bool):
            return value and other
        elif isinstance(other, ctypes._SimpleCData):
            return value and bool(other.value)
        else:
            return value and bool(other)

    def __hash__(self):
        return hash(self._as_parameter_)

class HANDLE(ULONG_PTR):
    """
    Wrapper around the numerical representation of a pointer to
    add checks for INVALID_HANDLE_VALUE
    """
    NULL = None
    INVALID = None

    def __init__(self, value=None):
        if value is None: value = 0
        super(HANDLE, self).__init__(value)
        self.autoclose = False

    @classmethod
    def from_param(cls, value):
        if value is None:
            return HANDLE(0)
        elif isinstance(value, ctypes._SimpleCData):
            return value
        else:
            return HANDLE(value)

    def close(self):
        if bool(self):
            try:
                CloseHandle(self)
            except:
                pass

    def __enter__(self):
        self.autoclose = True
        return self

    def __exit__(self, exc_typ, exc_val, trace):
        self.close()
        return False
    
    def __del__(self):
        if hasattr(self, 'autoclose') and self.autoclose:
            CloseHandle(self)

    def __nonzero__(self):
        return super(HANDLE, self).__nonzero__() and \
               self.value != HANDLE.INVALID.value

class GUID(ctypes.Structure):
    """ Borrowed small parts of this from the comtypes module. """
    _fields_ = [
        ('Data1', DWORD),
        ('Data2', WORD),
        ('Data3', WORD),
        ('Data4', (BYTE * 8)),
    ]

# Ctypes Structures
class LUID(ctypes.Structure):
    _fields_ = [
        ('LowPart', DWORD),
        ('HighPart', LONG),
    ]

class LUID_AND_ATTRIBUTES(LUID):
    _fields_ = [('Attributes', DWORD)]

class GenericReparseBuffer(ctypes.Structure):
    _fields_ = [('PathBuffer', UCHAR * MAX_GENERIC_REPARSE_BUFFER)]

class ReparsePoint(ctypes.Structure):
    """
    Originally, Buffer was a union made up of SymbolicLinkBuffer, MountpointBuffer,
    and GenericReparseBuffer. Since we're not actually doing anything with the buffer
    aside from passing it along to the native functions, however, I've gone ahead
    and cleaned up some of of the unnecessary code.
    """
    
    _fields_ = [
        ('ReparseTag', DWORD),
        ('ReparseDataLength', WORD),
        ('Reserved', WORD),
        ('ReparseGuid', GUID),
        ('Buffer', GenericReparseBuffer)
    ]

# Common uses of HANDLE
HANDLE.NULL = HANDLE()
HANDLE.INVALID = HANDLE(INVALID_HANDLE_VALUE)
LPHANDLE = POINTER(HANDLE)

# C Function Prototypes
CreateFile = kernel32.CreateFileW
CreateFile.restype = HANDLE
CreateFile.argtypes = [LPWSTR, DWORD, DWORD, LPVOID, DWORD, DWORD, HANDLE]

GetFileAttributes = kernel32.GetFileAttributesW
GetFileAttributes.restype = DWORD
GetFileAttributes.argtypes = [LPWSTR]

RemoveDirectory = kernel32.RemoveDirectoryW
RemoveDirectory.restype = BOOL
RemoveDirectory.argtypes = [LPWSTR]

CloseHandle = kernel32.CloseHandle
CloseHandle.restype = BOOL
CloseHandle.argtypes = [HANDLE]

GetCurrentProcess = kernel32.GetCurrentProcess
GetCurrentProcess.restype = HANDLE
GetCurrentProcess.argtypes = []

OpenProcessToken = advapi32.OpenProcessToken
OpenProcessToken.restype = BOOL
OpenProcessToken.argtypes = [HANDLE, DWORD, LPHANDLE]

LookupPrivilegeValue = advapi32.LookupPrivilegeValueW
LookupPrivilegeValue.restype = BOOL
LookupPrivilegeValue.argtypes = [LPWSTR, LPWSTR, POINTER(LUID_AND_ATTRIBUTES)]

AdjustTokenPrivileges = advapi32.AdjustTokenPrivileges
AdjustTokenPrivileges.restype = BOOL
AdjustTokenPrivileges.argtypes = [HANDLE, BOOL, LPVOID, DWORD, LPVOID, LPDWORD]

_DeviceIoControl = kernel32.DeviceIoControl
_DeviceIoControl.restype = BOOL
_DeviceIoControl.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPVOID]

def DeviceIoControl(hDevice, dwCtrlCode, lpIn, szIn, lpOut, szOut, lpOverlapped=None):
    """
    Wrapper around the real DeviceIoControl to return a tuple containing a bool indicating
    success, and a number containing the size of the bytes returned. (Also, lpOverlapped to
    default to NULL) """
    dwRet = DWORD(0)
    return bool(
        _DeviceIoControl(hDevice, dwCtrlCode, lpIn, szIn, lpOut, szOut, byref(dwRet), lpOverlapped)
    ), dwRet.value

def obtain_privileges(privileges):
    """
    Given a list of SE privilege names (eg: [ SE_CREATE_TOKEN_NAME, SE_BACKUP_NAME ]), lookup
    the privilege values for each and then attempt to acquire them for the current process.
    """
    global _obtained_privileges
    privileges = filter(lambda priv: priv not in _obtained_privileges, list(set(privileges)))
    privcount = len(privileges)
    if privcount == 0: return

    class TOKEN_PRIVILEGES(ctypes.Structure):
        # noinspection PyTypeChecker
        _fields_ = [
            ('PrivilegeCount', DWORD),
            ('Privileges', LUID_AND_ATTRIBUTES * privcount),
        ]

    with HANDLE() as hToken:
        tp = TOKEN_PRIVILEGES()
        tp.PrivilegeCount = privcount
        hProcess = GetCurrentProcess()
        if not OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES, byref(hToken)):
            raise WinError()

        for i, privilege in enumerate(privileges):
            tp.Privileges[i].Attributes = SE_PRIVILEGE_ENABLED
            if not LookupPrivilegeValue(None, privilege, byref(tp.Privileges[i])):
                raise Exception('LookupPrivilegeValue failed for privilege: {0}'.format(privilege))

        if not AdjustTokenPrivileges(hToken, False, byref(tp), sizeof(TOKEN_PRIVILEGES), None, None):
            raise WinError()

        _obtained_privileges.extend(privileges)

def open_file(filepath, flags=FILE_FLAG_OPEN_REPARSE_POINT, autoclose=False):
    """ Open file for read & write, acquiring the SE_BACKUP & SE_RESTORE privileges. """
    obtain_privileges([SE_BACKUP_NAME, SE_RESTORE_NAME])
    if (flags & FILE_FLAG_BACKUP_SEMANTICS) != FILE_FLAG_BACKUP_SEMANTICS:
        flags |= FILE_FLAG_BACKUP_SEMANTICS
    hFile = CreateFile(filepath, GENERIC_RW, FILE_SHARE_ALL, NULL, OPEN_EXISTING, flags, HANDLE.NULL)
    if not hFile: raise WinError()
    if autoclose: hFile.autoclose = True
    return hFile

def get_buffer(filepath, hFile=HANDLE.INVALID):
    """ Get a reparse point buffer. """
    if not hFile:
        hFile = open_file(filepath, autoclose=True)
    
    obj = ReparsePoint()
    result, dwRet = DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, None, 0L, byref(obj), MAX_REPARSE_BUFFER)
    return obj if result else None

def delete_reparse_point(filepath):
    """ Remove the reparse point folder at filepath. """
    dwRet = 0
    with open_file(filepath) as hFile:
        # Try to delete it first without the reparse GUID
        info = ReparsePoint()
        info.ReparseTag = 0
        result, dwRet = DeviceIoControl(hFile, FSCTL_DELETE_REPARSE_POINT, byref(info),
            REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, None, 0L)

        if not result:
            # If the first try fails, we'll set the GUID and try again
            buffer = get_buffer(filepath, hFile)
            info.ReparseTag = buffer.ReparseTag
            info.ReparseGuid = info.ReparseGuid
            result, dwRet = DeviceIoControl(hFile, FSCTL_DELETE_REPARSE_POINT, byref(info),
                REPARSE_GUID_DATA_BUFFER_HEADER_SIZE, None, 0L)
            if not result: raise WinError()
    
    if not RemoveDirectory(filepath):
        raise WinError()
    
    return dwRet

def is_reparse_point(filepath):
    """ Check whether or not filepath refers to a reparse point. """
    return hasflag(GetFileAttributes(filepath), FILE_ATTRIBUTE_REPARSE_POINT)

def rmtree(filepath, ignore_errors=False, onerror=None):
    """
    Re-implementation of shutil.rmtree that checks for reparse points
    (junctions/symbolic links) before iterating folders.
    """
    
    def rm(fn, childpath):
        try:
            fn(childpath)
        except:
            if not ignore_errors:
                if onerror is None:
                    raise
                else:
                    onerror(fn, childpath, sys.exc_info()[0])
    
    def visit_files(root, targets):
        for target in targets:
            rm(os.unlink, os.path.join(root, target))
    
    def visit_dirs(root, targets):
        for target in targets:
            childpath = os.path.join(root, target)
            rmtree(childpath, ignore_errors, onerror)
    
    if is_reparse_point(filepath):
        rm(delete_reparse_point, filepath)
        return
    
    for root, dirs, files in os.walk(filepath):
        visit_files(root, files)
        visit_dirs(root, dirs)
    
    rm(os.rmdir, filepath)

"""
Here's the original declaration used for the ReparsePoint class, just in case
someone is looking to try reading/writing from/to reparse points.

import math as _math

# Maximum buffer sizes
MAX_GENERIC_REPARSE_BUFFER = MAX_REPARSE_BUFFER - REPARSE_GUID_DATA_BUFFER_HEADER_SIZE
MAX_MOUNTPOINT_REPARSE_BUFFER = MAX_GENERIC_REPARSE_BUFFER - (sizeof(WORD) * 4)
MAX_SYMLINK_REPARSE_BUFFER = MAX_MOUNTPOINT_REPARSE_BUFFER - sizeof(DWORD)

# Need to factor in the size of wide characters for symlinks and mountpoint buffers.
_WCHAR_SIZE = ceil(sizeof(WCHAR))
_WCHAR_COUNT = lambda bufsize: int(_math.ceil( float(bufsize) / _WCHAR_SIZE ))

MAX_MOUNTPOINT_BUFFER_COUNT = _WCHAR_COUNT(MAX_SYMLINK_REPARSE_BUFFER)
MAX_SYMLINK_BUFFER_COUNT = _WCHAR_COUNT(MAX_SYMLINK_REPARSE_BUFFER)

del _WCHAR_SIZE, _WCHAR_COUNT

class ReparsePointBuffer(ctypes.Union):
    class SymbolicLinkBuffer(ctypes.Structure):
        _fields_ = [
            ('SubstituteNameOffset', WORD),
            ('SubstituteNameLength', WORD),
            ('PrintNameOffset', WORD),
            ('PrintNameLength', WORD),
            ('Flags', DWORD),
            ('PathBuffer', WCHAR * MAX_SYMLINK_BUFFER_COUNT)
        ]
    
    class MountPointBuffer(ctypes.Structure):
        _fields_ = [
            ('SubstituteNameOffset', WORD),
            ('SubstituteNameLength', WORD),
            ('PrintNameOffset', WORD),
            ('PrintNameLength', WORD),
            ('PathBuffer', WCHAR * MAX_MOUNTPOINT_BUFFER_COUNT)
        ]
    
    class GenericReparseBuffer(ctypes.Structure):
        _fields_ = [('PathBuffer', UCHAR * MAX_GENERIC_REPARSE_BUFFER)]

    _fields_ = [
        ('SymbolicLink', SymbolicLinkBuffer),
        ('MountPoint', MountPointBuffer),
        ('Generic', GenericReparseBuffer)
    ]

class ReparsePoint(ctypes.Structure):
    _fields_ = [
        ('ReparseTag', DWORD),
        ('ReparseDataLength', WORD),
        ('Reserved', WORD),
        ('ReparseGuid', GUID),
        ('_Buffer', ReparsePointBuffer)
    ]
    
    @property
    def Buffer(self):
        if self.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
            return self._Buffer.MountPoint
        elif self.ReparseTag == IO_REPARSE_TAG_SYMBOLIC_LINK:
            return self._Buffer.SymbolicLink
        else:
            return self._Buffer
"""
;

public by juntalis  880  0  3  0

Not-quite-compatible implementation of NASM's __utf16__ keyword for YASM.

Not-quite-compatible implementation of NASM's __utf16__ keyword for YASM.: utf16_for_yasm.asm
BITS 32

%macro __utf16__ 1
	%assign idx 1
	%xdefine wstring 
	%xdefine cstring %1
	%strlen cstrlen cstring
	%rep cstrlen
		%substr cchar cstring idx
		%if idx = 1
			%xdefine wstring cchar, 0x0
		%elif idx = cstrlen
			%xdefine wstring wstring cchar, 0x0
		%else
			%xdefine wstring wstring cchar, 0x0,
		%endif
		%assign idx idx+1
	%endrep
	db wstring
%endmacro

%define u(S) __utf16__ S

main:
	pushf
	pusha
	xor eax, eax
	add eax, wsDllPath - $
	ret
wsDllPath:
	u('injected_dll')
	dw 0x0


;

public by Charles Grunwald  1095  1  4  0

https://github.com/rwfpl/rewolf-wow64ext/blob/master/src/wow64ext.h converted to plain C

https://github.com/rwfpl/rewolf-wow64ext/blob/master/src/wow64ext.h converted to plain C: wow64ext.h
/**
 *
 * WOW64Ext Library
 *
 * Copyright (c) 2014 ReWolf
 * http://blog.rewolf.pl/
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#pragma once
#include <windows.h>

#ifndef STATUS_SUCCESS
#   define STATUS_SUCCESS 0
#endif

#ifdef __cplusplus
extern "C" {
#endif

#pragma pack(push)
#pragma pack(1)

#define _LIST_ENTRY_T(BITS) \
	struct _LIST_ENTRY##BITS \
	{ \
		DWORD##BITS Flink; \
		DWORD##BITS Blink; \
	}

#define _UNICODE_STRING_T(BITS) \
	struct _UNICODE_STRING##BITS \
	{ \
		union \
		{ \
			struct \
			{ \
				WORD Length; \
				WORD MaximumLength; \
			}; \
			DWORD##BITS dummy; \
		}; \
		DWORD##BITS Buffer; \
	}

#define _NT_TIB_T(BITS) \
	struct _NT_TIB##BITS \
	{ \
		DWORD##BITS ExceptionList; \
		DWORD##BITS StackBase; \
		DWORD##BITS StackLimit; \
		DWORD##BITS SubSystemTib; \
		DWORD##BITS FiberData; \
		DWORD##BITS ArbitraryUserPointer; \
		DWORD##BITS Self; \
	}

#define _CLIENT_ID_T(BITS) \
	struct _CLIENT_ID##BITS \
	{ \
		DWORD##BITS UniqueProcess; \
		DWORD##BITS UniqueThread; \
	}

#define _TEB_T_(BITS) \
	struct _TEB##BITS \
	{ \
		struct _NT_TIB##BITS NtTib; \
		DWORD##BITS EnvironmentPointer; \
		struct _CLIENT_ID##BITS ClientId; \
		DWORD##BITS ActiveRpcHandle; \
		DWORD##BITS ThreadLocalStoragePointer; \
		DWORD##BITS ProcessEnvironmentBlock; \
		DWORD LastErrorValue; \
		DWORD CountOfOwnedCriticalSections; \
		DWORD##BITS CsrClientThread; \
		DWORD##BITS Win32ThreadInfo; \
		DWORD User32Reserved[26]; \
	}

#define _LDR_DATA_TABLE_ENTRY_T(BITS) \
	struct _LDR_DATA_TABLE_ENTRY##BITS \
	{ \
		struct _LIST_ENTRY##BITS InLoadOrderLinks; \
		struct _LIST_ENTRY##BITS InMemoryOrderLinks; \
		struct _LIST_ENTRY##BITS InInitializationOrderLinks; \
		DWORD##BITS DllBase; \
		DWORD##BITS EntryPoint; \
		union \
		{ \
			DWORD SizeOfImage; \
			DWORD##BITS dummy01; \
		}; \
		struct _UNICODE_STRING##BITS FullDllName; \
		struct _UNICODE_STRING##BITS BaseDllName; \
		DWORD Flags; \
		WORD LoadCount; \
		WORD TlsIndex; \
		union \
		{ \
			struct _LIST_ENTRY##BITS HashLinks; \
			struct \
			{ \
				DWORD##BITS SectionPointer; \
				DWORD##BITS CheckSum; \
			}; \
		}; \
		union \
		{ \
			DWORD##BITS LoadedImports; \
			DWORD TimeDateStamp; \
		}; \
		DWORD##BITS EntryPointActivationContext; \
		DWORD##BITS PatchInformation; \
		struct _LIST_ENTRY##BITS ForwarderLinks; \
		struct _LIST_ENTRY##BITS ServiceTagLinks; \
		struct _LIST_ENTRY##BITS StaticLinks; \
		DWORD##BITS ContextInformation; \
		DWORD##BITS OriginalBase; \
		LARGE_INTEGER LoadTime; \
	}

#define _PEB_LDR_DATA_T(BITS) \
	struct _PEB_LDR_DATA##BITS \
	{ \
		DWORD Length; \
		DWORD Initialized; \
		DWORD##BITS SsHandle; \
		struct _LIST_ENTRY##BITS InLoadOrderModuleList; \
		struct _LIST_ENTRY##BITS InMemoryOrderModuleList; \
		struct _LIST_ENTRY##BITS InInitializationOrderModuleList; \
		DWORD##BITS EntryInProgress; \
		DWORD ShutdownInProgress; \
		DWORD##BITS ShutdownThreadId; \
	}

#define _PEB_T(BITS,NGF,A) \
	struct _PEB##BITS \
	{ \
		union \
		{ \
			struct \
			{ \
				BYTE InheritedAddressSpace; \
				BYTE ReadImageFileExecOptions; \
				BYTE BeingDebugged; \
				BYTE BitField; \
			}; \
			DWORD##BITS dummy01; \
		}; \
		DWORD##BITS Mutant; \
		DWORD##BITS ImageBaseAddress; \
		DWORD##BITS Ldr; \
		DWORD##BITS ProcessParameters; \
		DWORD##BITS SubSystemData; \
		DWORD##BITS ProcessHeap; \
		DWORD##BITS FastPebLock; \
		DWORD##BITS AtlThunkSListPtr; \
		DWORD##BITS IFEOKey; \
		DWORD##BITS CrossProcessFlags; \
		DWORD##BITS UserSharedInfoPtr; \
		DWORD SystemReserved; \
		DWORD AtlThunkSListPtr32; \
		DWORD##BITS ApiSetMap; \
		DWORD##BITS TlsExpansionCounter; \
		DWORD##BITS TlsBitmap; \
		DWORD TlsBitmapBits[2]; \
		DWORD##BITS ReadOnlySharedMemoryBase; \
		DWORD##BITS HotpatchInformation; \
		DWORD##BITS ReadOnlyStaticServerData; \
		DWORD##BITS AnsiCodePageData; \
		DWORD##BITS OemCodePageData; \
		DWORD##BITS UnicodeCaseTableData; \
		DWORD NumberOfProcessors; \
		union \
		{ \
			DWORD NtGlobalFlag; \
			NGF dummy02; \
		}; \
		LARGE_INTEGER CriticalSectionTimeout; \
		DWORD##BITS HeapSegmentReserve; \
		DWORD##BITS HeapSegmentCommit; \
		DWORD##BITS HeapDeCommitTotalFreeThreshold; \
		DWORD##BITS HeapDeCommitFreeBlockThreshold; \
		DWORD NumberOfHeaps; \
		DWORD MaximumNumberOfHeaps; \
		DWORD##BITS ProcessHeaps; \
		DWORD##BITS GdiSharedHandleTable; \
		DWORD##BITS ProcessStarterHelper; \
		DWORD##BITS GdiDCAttributeList; \
		DWORD##BITS LoaderLock; \
		DWORD OSMajorVersion; \
		DWORD OSMinorVersion; \
		WORD OSBuildNumber; \
		WORD OSCSDVersion; \
		DWORD OSPlatformId; \
		DWORD ImageSubsystem; \
		DWORD ImageSubsystemMajorVersion; \
		DWORD##BITS ImageSubsystemMinorVersion; \
		DWORD##BITS ActiveProcessAffinityMask; \
		DWORD##BITS GdiHandleBuffer[ A ]; \
		DWORD##BITS PostProcessInitRoutine; \
		DWORD##BITS TlsExpansionBitmap; \
		DWORD TlsExpansionBitmapBits[32]; \
		DWORD##BITS SessionId; \
		ULARGE_INTEGER AppCompatFlags; \
		ULARGE_INTEGER AppCompatFlagsUser; \
		DWORD##BITS pShimData; \
		DWORD##BITS AppCompatInfo; \
		struct _UNICODE_STRING##BITS CSDVersion; \
		DWORD##BITS ActivationContextData; \
		DWORD##BITS ProcessAssemblyStorageMap; \
		DWORD##BITS SystemDefaultActivationContextData; \
		DWORD##BITS SystemAssemblyStorageMap; \
		DWORD##BITS MinimumStackCommit; \
		DWORD##BITS FlsCallback; \
		struct _LIST_ENTRY##BITS FlsListHead; \
		DWORD##BITS FlsBitmap; \
		DWORD FlsBitmapBits[4]; \
		DWORD##BITS FlsHighIndex; \
		DWORD##BITS WerRegistrationData; \
		DWORD##BITS WerShipAssertPtr; \
		DWORD##BITS pContextData; \
		DWORD##BITS pImageHeaderHash; \
		DWORD##BITS TracingFlags; \
	}

#pragma warning(push)
#pragma warning(disable : 4142)

typedef DWORD DWORD32;

#pragma warning(pop)

_LIST_ENTRY_T(32);
_LIST_ENTRY_T(64);

_CLIENT_ID_T(32);
_CLIENT_ID_T(64);

typedef _UNICODE_STRING_T(32) UNICODE_STRING32;
typedef _UNICODE_STRING_T(64) UNICODE_STRING64;

typedef _LDR_DATA_TABLE_ENTRY_T(32) LDR_DATA_TABLE_ENTRY32;
typedef _LDR_DATA_TABLE_ENTRY_T(64) LDR_DATA_TABLE_ENTRY64;

typedef _TEB_T_(32) TEB32;
typedef _TEB_T_(64) TEB64;

typedef _PEB_LDR_DATA_T(32) PEB_LDR_DATA32;
typedef _PEB_LDR_DATA_T(64) PEB_LDR_DATA64;

typedef _PEB_T(32, DWORD64, 34) PEB32;
typedef _PEB_T(64, DWORD32, 30) PEB64;

#undef _LIST_ENTRY_T
#undef _UNICODE_STRING_T
#undef _NT_TIB_T
#undef _CLIENT_ID_T
#undef _TEB_T_
#undef _LDR_DATA_TABLE_ENTRY_T
#undef _PEB_LDR_DATA_T
#undef _PEB_T

typedef struct _XSAVE_FORMAT64
{
	WORD ControlWord;
	WORD StatusWord;
	BYTE TagWord;
	BYTE Reserved1;
	WORD ErrorOpcode;
	DWORD ErrorOffset;
	WORD ErrorSelector;
	WORD Reserved2;
	DWORD DataOffset;
	WORD DataSelector;
	WORD Reserved3;
	DWORD MxCsr;
	DWORD MxCsr_Mask;
	M128A FloatRegisters[8];
	M128A XmmRegisters[16];
	BYTE Reserved4[96];
} XSAVE_FORMAT64;

typedef struct _CONTEXT64
{
	DWORD64 P1Home;
	DWORD64 P2Home;
	DWORD64 P3Home;
	DWORD64 P4Home;
	DWORD64 P5Home;
	DWORD64 P6Home;
	DWORD ContextFlags;
	DWORD MxCsr;
	WORD SegCs;
	WORD SegDs;
	WORD SegEs;
	WORD SegFs;
	WORD SegGs;
	WORD SegSs;
	DWORD EFlags;
	DWORD64 Dr0;
	DWORD64 Dr1;
	DWORD64 Dr2;
	DWORD64 Dr3;
	DWORD64 Dr6;
	DWORD64 Dr7;
	DWORD64 Rax;
	DWORD64 Rcx;
	DWORD64 Rdx;
	DWORD64 Rbx;
	DWORD64 Rsp;
	DWORD64 Rbp;
	DWORD64 Rsi;
	DWORD64 Rdi;
	DWORD64 R8;
	DWORD64 R9;
	DWORD64 R10;
	DWORD64 R11;
	DWORD64 R12;
	DWORD64 R13;
	DWORD64 R14;
	DWORD64 R15;
	DWORD64 Rip;
	XSAVE_FORMAT64 FltSave;
	M128A Header[2];
	M128A Legacy[8];
	M128A Xmm0;
	M128A Xmm1;
	M128A Xmm2;
	M128A Xmm3;
	M128A Xmm4;
	M128A Xmm5;
	M128A Xmm6;
	M128A Xmm7;
	M128A Xmm8;
	M128A Xmm9;
	M128A Xmm10;
	M128A Xmm11;
	M128A Xmm12;
	M128A Xmm13;
	M128A Xmm14;
	M128A Xmm15;
	M128A VectorRegister[26];
	DWORD64 VectorControl;
	DWORD64 DebugControl;
	DWORD64 LastBranchToRip;
	DWORD64 LastBranchFromRip;
	DWORD64 LastExceptionToRip;
	DWORD64 LastExceptionFromRip;
} CONTEXT64;

// Below defines for .ContextFlags field are taken from WinNT.h
#ifndef CONTEXT_AMD64
#define CONTEXT_AMD64 0x100000
#endif

#define CONTEXT64_CONTROL (CONTEXT_AMD64 | 0x1L)
#define CONTEXT64_INTEGER (CONTEXT_AMD64 | 0x2L)
#define CONTEXT64_SEGMENTS (CONTEXT_AMD64 | 0x4L)
#define CONTEXT64_FLOATING_POINT  (CONTEXT_AMD64 | 0x8L)
#define CONTEXT64_DEBUG_REGISTERS (CONTEXT_AMD64 | 0x10L)
#define CONTEXT64_FULL (CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_FLOATING_POINT)
#define CONTEXT64_ALL (CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_SEGMENTS | CONTEXT64_FLOATING_POINT | CONTEXT64_DEBUG_REGISTERS)
#define CONTEXT64_XSTATE (CONTEXT_AMD64 | 0x20L)

#pragma pack(pop)

#ifdef WOW64EXT_EXPORTS
#   define SPEC dllexport
#else
#   define SPEC dllimport
#endif

__declspec(SPEC) DWORD64 __cdecl X64Call(DWORD64 func, int argC, ...);
__declspec(SPEC) DWORD64 __cdecl GetModuleHandle64(wchar_t* lpModuleName);
__declspec(SPEC) DWORD64 __cdecl GetProcAddress64(DWORD64 hModule, char* funcName);
__declspec(SPEC) SIZE_T __cdecl VirtualQueryEx64(HANDLE hProcess, DWORD64 lpAddress, MEMORY_BASIC_INFORMATION64* lpBuffer, SIZE_T dwLength);
__declspec(SPEC) DWORD64 __cdecl VirtualAllocEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect);
__declspec(SPEC) BOOL __cdecl VirtualFreeEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD dwFreeType);
__declspec(SPEC) BOOL __cdecl VirtualProtectEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flNewProtect, DWORD* lpflOldProtect);
__declspec(SPEC) BOOL __cdecl ReadProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead);
__declspec(SPEC) BOOL __cdecl WriteProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten);
__declspec(SPEC) BOOL __cdecl GetThreadContext64(HANDLE hThread, CONTEXT64* lpContext);
__declspec(SPEC) BOOL __cdecl SetThreadContext64(HANDLE hThread, CONTEXT64* lpContext);
__declspec(SPEC) VOID __cdecl SetLastErrorFromX64Call(DWORD64 status);

#ifdef __cplusplus
}
#endif


;