Question

Comment savoir par programme en C # si un fichier DLL non géré est x86 ou x64?

Était-ce utile?

La solution

Consultez les spécifications . Voici une implémentation de base:

public static MachineType GetDllMachineType(string dllPath)
{
    // See http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
    // Offset to PE header is always at 0x3C.
    // The PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00,
    // followed by a 2-byte machine type field (see the document above for the enum).
    //
    FileStream fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    fs.Seek(0x3c, SeekOrigin.Begin);
    Int32 peOffset = br.ReadInt32();
    fs.Seek(peOffset, SeekOrigin.Begin);
    UInt32 peHead = br.ReadUInt32();

    if (peHead!=0x00004550) // "PE\0\0", little-endian
        throw new Exception("Can't find PE header");

    MachineType machineType = (MachineType) br.ReadUInt16();
    br.Close();
    fs.Close();
    return machineType;
}

Le code MachineType est défini comme suit:

public enum MachineType : ushort
{
    IMAGE_FILE_MACHINE_UNKNOWN = 0x0,
    IMAGE_FILE_MACHINE_AM33 = 0x1d3,
    IMAGE_FILE_MACHINE_AMD64 = 0x8664,
    IMAGE_FILE_MACHINE_ARM = 0x1c0,
    IMAGE_FILE_MACHINE_EBC = 0xebc,
    IMAGE_FILE_MACHINE_I386 = 0x14c,
    IMAGE_FILE_MACHINE_IA64 = 0x200,
    IMAGE_FILE_MACHINE_M32R = 0x9041,
    IMAGE_FILE_MACHINE_MIPS16 = 0x266,
    IMAGE_FILE_MACHINE_MIPSFPU = 0x366,
    IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466,
    IMAGE_FILE_MACHINE_POWERPC = 0x1f0,
    IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1,
    IMAGE_FILE_MACHINE_R4000 = 0x166,
    IMAGE_FILE_MACHINE_SH3 = 0x1a2,
    IMAGE_FILE_MACHINE_SH3DSP = 0x1a3,
    IMAGE_FILE_MACHINE_SH4 = 0x1a6,
    IMAGE_FILE_MACHINE_SH5 = 0x1a8,
    IMAGE_FILE_MACHINE_THUMB = 0x1c2,
    IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169,
}

Je n’avais besoin que de trois d’entre eux, mais je les ai tous inclus par souci d’exhaustivité. Vérification finale 64 bits:

// Returns true if the dll is 64-bit, false if 32-bit, and null if unknown
public static bool? UnmanagedDllIs64Bit(string dllPath)
{
    switch (GetDllMachineType(dllPath))
    {
        case MachineType.IMAGE_FILE_MACHINE_AMD64:
        case MachineType.IMAGE_FILE_MACHINE_IA64:
            return true;
        case MachineType.IMAGE_FILE_MACHINE_I386:
            return false;
        default:
            return null;
    }
}

Autres conseils

À l'aide d'une invite de commande Visual Studio, dumpbin / headers nomdll.dll fonctionne également. Sur ma machine, le début de la sortie indiquait:

FILE HEADER VALUES
8664 machine (x64)
5 number of sections
47591774 time date stamp Fri Dec 07 03:50:44 2007

Encore plus simple: consultez la classe System.Reflection.Module. Il inclut la méthode GetPEKind, qui renvoie 2 énumérations décrivant le type de code et la cible de la CPU. Plus d'hexagone!

(le reste de ce message très informatif a été copié sans vergogne depuis http : //www.developersdex.com/vb/message.asp? p = 2924 & amp; r = 6413567 )

Exemple de code:

Assembly assembly = Assembly.ReflectionOnlyLoadFrom(@"<assembly Path>");
PortableExecutableKinds kinds;
ImageFileMachine imgFileMachine;
assembly.ManifestModule.GetPEKind(out kinds, out imgFileMachine);

PortableExecutableKinds peut être utilisé pour vérifier quel type d'assembly. Il a 5 valeurs:

ILOnly: l'exécutable contient uniquement le langage intermédiaire Microsoft (MSIL), et est donc neutre par rapport à 32 bits ou 64 bits plates-formes.

NotAPortableExecutableImage: le fichier n'est pas dans un exécutable portable (PE) format de fichier.

PE32Plus: l'exécutable nécessite une plate-forme 64 bits.

Required32Bit: l'exécutable peut être exécuté sur une plate-forme 32 bits ou dans le Environnement Windows sur Windows (WOW) 32 bits sur une plate-forme 64 bits.

Unmanaged32Bit: l'exécutable contient du code pur non géré.

Voici les liens:

Méthode Module.GetPEKind: http://msdn.microsoft.com/fr us / library / system.reflection.module.getpekind.aspx

Énumération PortableExecutableKinds: http://msdn.microsoft.com /en-us/library/system.reflection.portableexecutablekinds(VS.80).aspx

Énumération ImageFileMachine: http://msdn.microsoft.com/en-us/ bibliothèque / system.reflection.imagefilemachine.aspx

Au lieu de Assembly.LoadFile , utilisez Assembly.ReflectionOnlyLoadFrom . Cela vous permettra de contourner le " Format d'image incorrect " exceptions.

Je sais que cela fait longtemps que cette mise à jour a été effectuée. J'ai été capable de sortir avec le "Format d'image incorrect". exceptions en chargeant le fichier dans son propre AppDomain.

        private static (string pkName, string imName) FindPEKind(string filename)
    {
        // some files, especially if loaded into memory
        // can cause errors. Thus, load into their own appdomain
        AppDomain tempDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
        PEWorkerClass remoteWorker =
            (PEWorkerClass)tempDomain.CreateInstanceAndUnwrap(
                typeof(PEWorkerClass).Assembly.FullName,
                typeof(PEWorkerClass).FullName);

        (string pkName, string imName) = remoteWorker.TryReflectionOnlyLoadFrom_GetManagedType(filename);

        AppDomain.Unload(tempDomain);
        return (pkName, imName);
    }

À ce stade, je procède comme suit:

        public (string pkName, string imName) TryReflectionOnlyLoadFrom_GetManagedType(string fileName)
    {
        string pkName;
        string imName;
        try
        {
            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(assemblyFile: fileName);
            assembly.ManifestModule.GetPEKind(
                peKind: out PortableExecutableKinds peKind,
                machine: out ImageFileMachine imageFileMachine);

            // Any CPU builds are reported as 32bit.
            // 32bit builds will have more value for PortableExecutableKinds
            if (peKind == PortableExecutableKinds.ILOnly && imageFileMachine == ImageFileMachine.I386)
            {
                pkName = "AnyCPU";
                imName = "";
            }
            else
            {
                PortableExecutableKindsNames.TryGetValue(
                    key: peKind,
                    value: out pkName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    pkName = "*** ERROR ***";
                }

                ImageFileMachineNames.TryGetValue(
                    key: imageFileMachine,
                    value: out imName);
                if (string.IsNullOrEmpty(value: pkName))
                {
                    imName = "*** ERROR ***";
                }
            }

            return (pkName, imName);
        }
        catch (Exception ex)
        {
            return (ExceptionHelper(ex), "");
        }
    }

Cette opération sur mon répertoire Widows \ Assembly ne me donne aucune erreur avec plus de 3600 fichiers traités. remarque: j'utilise un dictionnaire pour charger les valeurs renvoyées.

J'espère que ça aide. YMMV

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top