Error lnk2026 module unsafe for safeseh image

I got this error when building a sample visual C++ project. First I downloaded 3 sample projects, all solve the same problem, print out all the prime numbers less than N (you may know these sample

I got this error when building a sample visual C++ project.
First I downloaded 3 sample projects, all solve the same problem, print out all the prime numbers less than N (you may know these sample projects ?). I built the pure-C project without any problem. But when I tried to build the assembly-based project one, I got this error.

Thank you.

CloudyMarble's user avatar

CloudyMarble

36.5k70 gold badges95 silver badges129 bronze badges

asked Feb 5, 2013 at 15:06

Hoai Dam's user avatar

2

In Visual Studio 2012 Express Edition:

Right-click on your project ->
Properties -> 
Configuration Properties ->
Linker ->
Advanced and changed "Image Has Safe Exception Handlers" to "No (/SAFESEH:NO)"

answered Mar 13, 2014 at 2:34

kungfooman's user avatar

kungfoomankungfooman

4,2271 gold badge42 silver badges30 bronze badges

A picture is worth 0x3e8 words for the /SAFESEH:NO linker setting:

enter image description here

Or you can tell MASM to provide a guarantee that the object contains no exception handlers or that any exception handlers are defined with .SAFESEH, if you know that to be correct for your assembly code:

enter image description here

This will allow you to keep /SAFESEH enabled for the project’s linking. But is it correct? You are making the guarantee! Be sure or use the first option.

answered Feb 10, 2015 at 22:36

chappjc's user avatar

chappjcchappjc

30.2k6 gold badges75 silver badges130 bronze badges

Try to disable SAFESEH.

From spec: /SAFESEH was specified, but a module was not compatible with the safe exception handling feature.

answered Feb 5, 2013 at 15:21

Leo Chapiro's user avatar

Leo ChapiroLeo Chapiro

13.5k7 gold badges60 silver badges92 bronze badges

3

  • Remove From My Forums
  • Question

  • Hi

    I am migrating my application from vc++6.0 to vc++2013

    I have copied sql10forcompile in my machine from older machine were vc++6.0 was there, Sql10Compile is using to build the embedded cp code to cpp file.

    I am getting this error after i copy it in my current machine and this error directs to a lib file libcs.lib(libcs.dll)

    can anyone help me

    Thanks Ankush

Answers

  • Hi Ankush,

    Thank you for your feedback!

    I feel it is strange. Please check as below:

    right-click your project -> properties

    configuration properties -> linker -> advanced

    Best regards,

    Sunny

    • Marked as answer by

      Thursday, January 30, 2014 5:41 AM

  • Hi,

    Actually we have to click on command line right. I have resolved the syntax issue by the way.

    And i checked the linker->advanced option .. for me it was Yes(/SAFESEH) tahts it. Is it fine coz it is not showing any error now

    Thanks Ankush

    • Marked as answer by
      Anna Cc
      Thursday, January 30, 2014 5:43 AM

Permalink

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

cpp-docs/docs/error-messages/tool-errors/linker-tools-error-lnk2026.md

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK2026

Linker Tools Error LNK2026

11/04/2016

LNK2026

LNK2026

9955bf7c-59b5-4fa1-8481-147db0d7df45

module unsafe for SAFESEH image

/SAFESEH was specified, but a module was not compatible with the safe exception handling feature. If you want to use this module with /SAFESEH, then you will need to recompile the module.

Subscribe to Benohead (RSS)

Using Visual Studio 2012, I was building from the command line a software which was built until now using an older version (guess it was Visual Studio 2005). There were of course many things I had to change in the code itself (so much for portability…). And of course I had to upgrade the project in the solutions to VS2012 (using the devenv /upgrade command).

After converting the projects and modifying the code, I got the following error messages on a few projects:

error LNK2026: module unsafe for SAFESEH image.

fatal error LNK1281: Unable to generate SAFESEH image.

This means that the linker was started with the option meaning /SAFESEH “image has safe exception handlers” (also note that we only got this because we’re still building 32bit targets). The error occurs because some input modules were not compatible with the safe exception handlers feature of the linker. In our case it was some third party lib files for which I did not have the source code. These lib files are not be compatible with safe exception handlers is because they were created with an older version of the Visual C++ compiler.

But this is easy to fix. You just need to tell the linker not to produce an image with a table of safe exceptions handlers even if it thinks that all modules are compatible with the safe exception handling feature.

If you work in the Visual Studio Editor, you can right-click on your DLL project, go to Properties > Linker > Advanced and set “image has safe exception handlers” to No.

If like me you’re working from the command line, you can edit the .vcxproj file by opening it and searching for the <link> tags. Add the following to each <link> tag (there will be one per target e.g. one for debug and one for release):

<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>

It doesn’t matter where exactly you add it, it just needs to be between <link> and </link>.

If you call the linker yourself, you can also add /SAFESEH:NO to the command line.

After making this change, you can build your project again and the error will be gone.

Да возможно не в этих разделах надо было тему делать, но я просто подумал что раз Dll эта читерская с ассемблерным кодом, то вполне подойдёт раздел «Вопросов по созданию читов»))))

Да на счёт гугла, я сразу же прогуглил, так же наткнулся на тему которую ты первую указал (в нгей я нефига не понял), но 2 тему я не находил к сожалению(( Спасибо к стате что нашёл мою проблему))) Щас попробую сделать как ты написал.

Ура!)) Собрался наконец мой файлик))

Да к стате, 1 вопросик чуть не по теме, как для этого скрипта сделать правильный pattern и вообще как правильно найти все эти байты? А то я дак не оч пока понимаю от куда это всё берётся.

Да… вот скрипт на всякий:

Скрипт я делал по подобию скипта Coder’а.

#include <Windows.h>#include <fcntl.h>#include <stdio.h>#include <io.h>#include <Psapi.h>#include <detours.h>#pragma comment (lib, "psapi.lib")DWORD WINAPI SpinTires_thread(LPVOID);DWORD retn_addr = 0;DWORD ohk = false;DWORD APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved){	switch (ul_reason_for_call)	{	case DLL_PROCESS_ATTACH:		CreateThread(NULL, NULL, SpinTires_thread, NULL, NULL, NULL);	case DLL_THREAD_ATTACH:	case DLL_THREAD_DETACH:	case DLL_PROCESS_DETACH:		break;	}	return true;}MODULEINFO GetModuleData(char*module_name){	MODULEINFO moduleInf = { 0 };	HMODULE hModule = GetModuleHandle(module_name);	if (hModule == NULL)		return moduleInf;	GetModuleInformation(GetCurrentProcess(), hModule, &moduleInf, sizeof(MODULEINFO));	return moduleInf;}bool DataCompare(const BYTE*pData, const BYTE*pattern, const char*mask){	for (; *mask; ++mask, ++pData, ++pattern)		if (*mask == 'x' && *pData != *pattern)			return false;	return (*mask) == NULL;}DWORD FindPattern(DWORD start_address, DWORD lenght, BYTE*pattern, char*mask){	for (DWORD i = 0; i < lenght; i++)		if (DataCompare((BYTE*)(start_address + i), pattern, mask))			return (DWORD)(start_address + i);	return NULL;}void InfinityHealth(){	_asm	{		mov dword ptr[ecx + 0xF0], 0x0		jmp retn_addr	}}DWORD WINAPI SpinTires_thread(LPVOID){	MODULEINFO moduleInf = GetModuleData("SpinTires.exe");	DWORD old_prot = 0;	DWORD ohk_address = FindPattern((DWORD)moduleInf.lpBaseOfDll, moduleInf.SizeOfImage,		(PBYTE)"x8Bx91xF0x00x00x00xDB", "xxxxxxxxxxx");	ohk_address += 0x3;	retn_addr = ohk_address + 0x6;	BYTE nops[3] = { 0x90, 0x90, 0x90 };	BYTE original[6] = { 0x8B, 0x91, 0xF0, 0x00, 0x00, 0x00 };	for (;; Sleep(75))	{		if (GetAsyncKeyState(VK_NUMPAD2) & 0x8000)		{			if (!ohk)			{				DetourFunction((PBYTE)ohk_address, (PBYTE)InfinityHealth);				VirtualProtect(InfinityHealth, 3, PAGE_EXECUTE_READWRITE, &old_prot);				memcpy(InfinityHealth, nops, 3);				VirtualProtect(InfinityHealth, 3, old_prot, &old_prot);				ohk = true;			}			else			{				VirtualProtect((void*)ohk_address, sizeof(original), PAGE_EXECUTE_READWRITE, &old_prot);				memcpy((void*)ohk_address, original, sizeof(original));				VirtualProtect((void*)ohk_address, sizeof(original), old_prot, &old_prot);				ohk = false;			}		}	}}


Изменено 28 октября, 2014 пользователем Xipho

Hello, you are right,

the issue is the same for clang (http://software.intel.com/en-us/forums/showthread.php?t=102603&o=a&s=lr), C++x0std::copy_exception was renamed tostd::make_exception_ptr in final version of C++11 standard. So you need to either rename it in the header or define /DTBB_USE_CAPTURED_EXCEPTION=1 to not use exception_ptr like for old compilers.

We are working on how is better to support both cases at once (i.e. vs2010 and vs2012).

thanks for the report

—Vladimir

Update — details on the issue:

I’m trying out the release candidate of Visual Studio 2012. tbb_exception.h does not compile due to use of std::copy_exception(). I’m having a hard time finding any info on this method. Is it really part of the std namespace?

I just done verifications with different versions/editions ofVisual Studioand MinGW. Here are results:

— Visual Studio 2005 Professional Edition- ‘copy_exception’ is not supported

— Visual Studio 2008Express Edition- ‘copy_exception’ is not supported

— Visual Studio 2010Express Edition- ‘copy_exception’ issupported in ‘exception‘ header file

-MinGW v3.4.2- ‘copy_exception’ is not supported

I don’tthinkthat Microsoft will remove that support inVisual Studio 2012.

I don’tthinkthat Microsoft will remove that support inVisual Studio 2012.

I bet it will since it is out of C++11 standard.

—Vladimir

I don’tthinkthat Microsoft will remove that support inVisual Studio 2012.

I bet it will since it is out of C++11 standard…

That is possible. But, Microsoft is «famous» for braking or ignoring,too some degree, standards. OpenGL and OpenMP are
the best examples.

Looks like you’re wrong. Currently Microsoft make sure to be as close as possible to the C++ standard, and the previous naming was intended to provide the functionality before standardization, making it obvious that if you used it you would be potentially subject to need to change the code in former versions of the compiler.

I don’t know what you mean by OpengGl?

———

So, I took the last TBB release file and tryed to compile the tbb project in VS2012.
After having replaced std::copy_exception to std::make_exception_ptr, I got this strange error and I can’t find how to fix it:

2>atomic_support.obj : error LNK2026: module unsafe for SAFESEH image.
2>lock_byte.obj : error LNK2026: module unsafe for SAFESEH image.
2>     Creating library E:[...]tbb_debug.lib and object E:[...]tbb_debug.exp
2>E:[...]tbb_debug.dll : fatal error LNK1281: Unable to generate SAFESEH image.

Any idea?

The only solution to this problem I found so far is to deactivate SAFESEH from the project file…

Any better idea.

The only solution to this problem I found so far is to deactivate SAFESEH from the project file…

Any better idea.

I just looked at MSDN and your simplesolution looks good. Also, this is whatMSDN says:

Error LNK2026:
/SAFESEH was specified, but a module was not compatible with the safe exception handling feature. If you want to use
this module with /SAFESEH, then you will need to recompile the module using the Visual C++ .NET 2003 (or later) compiler.

Did you try to re-build the TBB librarywith /SAFESEH?

That is possible. But, Microsoft is «famous» for braking or ignoring,too some degree, standards. OpenGL and OpenMP are
the best examples

IIRC OpenGL is layered on the top of Direct3D.

Did you try to re-build the TBB librarywith /SAFESEH?

It IS when I have this flag set that I have this error.

What I did, to be precise, is :

1. get the TBB sources archive file
2. open tbb project file in VS2012, which trigger the automatic project conversion (because the other one was from older vs version)
3. after project conversion, I have a cmake script injecting this tbb project in my big set of projects

So, the /SAFESEH flag is set «by default».
It’s the assembly code makes the flag trigger the link error. If I set /SAFESEH:NO it works.

I checked: the problem occurs only with converted project files as the compiler needs to be sure it is compatible with the new runtime. So, here the problem is that it would compile if the assembly code was not present (and considered not compatible with the crt or something like that). Compiling without the flag might hide a potential problem if I understood correctly.
I guess a good way to fix this would be to use std::atomic instead of providing the assembly code, OR to provide it in a way that makes it compiled by the C++ compiler instead of a separate compiler (because it seems it’s compiled separately.

My understanding of the problem is obviously not complete, but I also need to be sure that using tbb on a recent VS compiler will no generate hard to spot problems…


2. open tbb project file in
VS2012, which trigger the automatic project conversion (because the other one was from older vs version)…
My understanding of the problem is obviously not complete, but I also need to be sure that using tbb on a
recent VS compiler will no generate hard to spot problems…

Unfortunately, I can’t verify it because I have Visual Studios 2005 Pro, 2008Pro / Express and 2010Express, and
there are no any plans to buy the2012 version.

I just checked a version of TBB installed on my primary development machine and it is aCommercially Alligned version 4 Update 3.
Also, there are only 5 *.asm files in different TBB folders. What asm-file is causing that problem?

Yes not all the assemby files are in the VS project file, some are in but marked as to be ignored (I tried only with a 32bit build).

The active ones:

-itbb/src/tbb/ia32-masm/atomic_support.asm

-itbb/src/tbb/ia32-masm/lock_byte.asm

The ignored ones but visible in the project once open in VS:

— itbb/src/tbb/intel64-masm/atomic_support.asm

-itbb/src/tbb/intel64-masm/intel64_misc.asm

These last files are deactivated because it’s a 32bit target I am building for the moment.

You should be able to see them by getting the last archive and opening the tbb.vsproj file with whatever VS you have.

paul3579> Read the beginning of the thread, there is already an answer about this.


1. get the TBB sources archive file
2. open tbb project file in VS2012, which trigger the automatic project conversion (because the other one was from older vs version)
3. after project conversion, I have a cmake script injecting this tbb project in my big set of projects

So, the /SAFESEH flag is set «by default».
It’s the assembly code makes the flag trigger the link error.

If I set /SAFESEH:NO it works

I verified Update 1 and Update 3 of TBB version 4. For a 32-bitTBB DLL librarytwo asm-files are always compiled:

..ia32-masmlock_byte.asm
..ia32-masmatomic_support.asm

andfor both asm-files a project option’Use Safe Exception Handlers‘ was set to ‘No‘ ( in both TBB releases ).
It looks like some changes are made in a latest release of TBB.

I see.

I’ve read the CHANGES file but I see nothing related to this.

Should this option be changed back to NO for these files for the next release?

I see.

I’ve read the CHANGES file but I see nothing related to this.

Should this option be changed back to NO for these files for the next release?

It is not clear. I think TBB developers should explain why the option was changedto ‘Yes‘.

I just upgraded to v4.1 Update 2 and this «error LNK2026: module unsafe for SAFESEH image.» problem isn’t fixed yet.

It’s annoying because I can’t automate easily the change in the VS project file and I have to remember what it was about each time I upgrade TBB.

I just upgraded to v4.1 Update 2 and this «error LNK2026: module unsafe for SAFESEH image.» problem isn’t fixed yet.

It’s annoying because I can’t automate easily the change in the VS project file and I have to remember what it was about each time I upgrade TBB.

Hello

I’ve the same problem & found the solution, it’s simple… just enable safeseh for atomic_support.asm & lock_byte.asm,

(right click the asm files: PropertiesMicrosoft Macro AssemblerAdvancedUse Safe Exception Handlers)

Once again, the fix is easy and already reported, but hard to automatize with scripts to integrate tbb into a project and be able to update it easily.

Right,

We are looking how to support all 3 versions of visual studio without such issues and not introducing extra overhead…

—Vladimir

Я использую бета-версию Microsoft Visual Studio 2011 Professional

Я пытаюсь запустить файлы OpenCV С++ (http://opencv.willowgarage.com/wiki/Welcome), которые я скомпилировал с использованием cMake и Compliance для Visual Studio.

Однако, когда я иду на отладку проекта, я получаю более 600 ошибок, большинство из которых:

ошибка LNK2026: модуль небезопасен для изображения SAFESEH.

По-видимому, эти файлы находятся в проекте opencv_ffmpeg, но я не смог их найти, я просмотрел страницу Safeesception Handels SafeesEx на странице справки Microsoft, но я не смог найти окончательных ответов.

Мне было интересно, есть ли у кого-нибудь еще эта проблема, и если им удалось это исправить.

15 май 2012, в 14:18

Поделиться

Источник

5 ответов

Из комментариев:

Это происходит, когда вы связываете .obj или .lib, который содержит код, созданный более ранней версией компилятора. Это, конечно, было бы общим, если вы загрузили двоичный файл для opencv_ffmpeg вместо источника. Вы можете отключить параметр компоновщика, но тогда у вас все еще будет несовместимость версии CRT, которая может быть байтом. Восстановите библиотеку из источника. — Ханс Пассант 15 мая в 13:01

Спасибо за помощь, это сработало — Аарон Томпсон 17 мая в 14:50

Bo Persson
19 окт. 2012, в 19:53

Поделиться

Отключение опции «Изображение имеет безопасные обработчики исключений» в свойствах проекта → Свойства конфигурации → вкладка Linker → Advanced помогла мне.

Ievgen
03 нояб. 2013, в 17:43

Поделиться

Другим способом является добавление некоторого обработчика SEH (например, пустого) в asm файлы и компиляция с опцией /safeseh, а затем компилирование другого кода с помощью опции /SAFESEH:YES компилятора.

Пустой обработчик SEH:

.safeseh SEH_handler

SEH_handler   proc
;handler
ret

SEH_handler   endp

DitherSky
10 сен. 2014, в 18:19

Поделиться

Если вы получили эту ошибку при создании ZLIB в Visual Studio, это решение. Найдите contribmasmx86bld_ml32.bat и добавьте /safeseh в качестве опции

До

ml /coff /Zi /c /Flmatch686.lst match686.asm
ml /coff /Zi /c /Flinffas32.lst inffas32.asm

После

ml /safeseh /coff /Zi /c /Flmatch686.lst match686.asm
ml /safeseh /coff /Zi /c /Flinffas32.lst inffas32.asm

Nayana Adassuriya
27 нояб. 2017, в 11:40

Поделиться

Ваш пробег может отличаться, но ни один из вышеперечисленных предложений не работал у меня (хотя я не пытался запустить собственный обработчик исключения asm).

Какова была работа по выбору цели сборки Release/x64.

Я запускаю Windows 10 на 64-разрядной машине и использую Visual Studio 2015.

Также работает целевая версия Release/Win32. Я думаю, главное — выбрать «Release».

Bob Stine
15 май 2017, в 18:58

Поделиться

Ещё вопросы

  • 0Как удалить элементы и массив по двум атрибутам в AngularJS?
  • 0Новый вид «Tab level» в Ionic
  • 1(Java) Получение ошибки с 2D-игрой
  • 1Java SimpleDateFormat не принимает ## / ##
  • 0HTML / CSS проблема с элементами, движущимися при разных разрешениях экрана
  • 0mysql.exe выходной файл CSV в Windows
  • 1MetadataMBeanInfoAssembler не поддерживает динамические прокси JDK
  • 0Почему array_map не работает здесь?
  • 0Создание сценариев HTML с использованием Visual Studio 2012 Express для Интернета
  • 1Как читать файл .doc?
  • 0Как можно использовать Express JS вместе с Google Chart
  • 0Ионная функция запуска приложения при втором нажатии
  • 0Не работает директива в угловых
  • 0Выравнивание div в середине не работает
  • 1Массивы заполняются нулями вместо имен и 0 вместо чисел
  • 1реагировать родной — Как использовать состояние в конструкторе
  • 1chrome.runtime.onMessage.addListener не определен в скрипте содержимого
  • 1Как добавить легенду в Basemap с помощью Python
  • 0php выдает ошибку no no timezone при новой настройке
  • 1преобразовать массив numpy из объекта dtype в float
  • 1Vuejs — передать слот вложенному ребенку
  • 0Allegro al_load_ttf_font не может найти файл
  • 1Секретные ключи различаются между Android и сервером
  • 0Таблица в DIV и CSS
  • 0поменять имена классов с помощью jquery [duplicate]
  • 1Пытаюсь почистить стол с помощью панд из результатов Selenium
  • 0Chrome Hard Reload с использованием JS
  • 0Использование мобильных служб Azure в приложении C ++
  • 0Как мне установить 2 или более переключателей для каждой строки данных в таблице?
  • 0Ведите конверсию с помощью мобильного приложения salesforce
  • 1Проверка данных формы с помощью Javascript
  • 1Аналоговый спидометр
  • 0Ошибка запуска углового сервера
  • 1Как организовать макет используя PyQt
  • 1XStream: UnknownFieldException — Нет такого поля
  • 0AscW эквивалент из VB в C ++
  • 0Проектирование базы данных — система «много ко многим» или «один ко многим»?
  • 1Вопрос по повороту оси X на Android
  • 0Как лучше организовать C ++ Socket Server?
  • 1Сортировать строки даты на карте [дубликаты]
  • 1Не удается найти файл виновника в моем проекте Android даже после расширения основной папки
  • 1Проверка формы Javascript | установить определенный формат ввода
  • 1Как рассчитать дублирование функций (или конструирование объектов Ridit) индивидуально на пандах
  • 0почему mozilla не поддерживает $ в jquery?
  • 1Проверьте соседнюю точку в 2d массиве с граничными условиями
  • 1Перехватить наOptionsItemSelected
  • 1Альфа-составные изображения с использованием emgu.cv
  • 1Как изменить версию проекта установки
  • 1Как получить значения панд MultiIndex в виде списка?
  • 0Html5 полноэкранный браузер Toggle Button

Сообщество Overcoder

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error loader couldn t initialize service
  • Error load settings что это
  • Error load settings как исправить ошибку при запуске
  • Error lnk2019 ссылка на неразрешенный внешний символ imp
  • Error lnk2019 ссылка на неразрешенный внешний символ declspec dllimport

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии