Номер ошибки: | Ошибка 487 | |
Название ошибки: | Windows Error 487 | |
Описание ошибки: | Ошибка 487: Возникла ошибка в приложении Windows. Приложение будет закрыто. Приносим извинения за неудобства. | |
Разработчик: | Microsoft Corporation | |
Программное обеспечение: | Windows | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Анализ «Windows Error 487»
«Windows Error 487» — это стандартная ошибка времени выполнения. Когда дело доходит до программного обеспечения, как Windows, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. К сожалению, иногда ошибки, такие как ошибка 487, могут быть пропущены во время этого процесса.
После первоначального выпуска пользователи Windows могут столкнуться с сообщением «Windows Error 487» во время запуска программы. Если возникает ошибка 487, разработчикам будет сообщено об этой проблеме через уведомления об ошибках, которые встроены в Windows. Затем Microsoft Corporation нужно будет исправить эти ошибки в главном исходном коде и предоставить модифицированную версию для загрузки. Если есть уведомление об обновлении Windows, это может быть решением для устранения таких проблем, как ошибка 487 и обнаруженные дополнительные проблемы.
Сбой во время запуска Windows или во время выполнения, как правило, когда вы столкнетесь с «Windows Error 487». Вот три наиболее распространенные причины, по которым происходят ошибки во время выполнения ошибки 487:
Ошибка 487 Crash — ошибка 487 блокирует любой вход, и это может привести к сбою машины. Это происходит много, когда продукт (Windows) или компьютер не может обрабатывать уникальные входные данные.
«Windows Error 487» Утечка памяти — Ошибка 487 утечка памяти происходит и предоставляет Windows в качестве виновника, перетаскивая производительность вашего ПК. Потенциальные триггеры могут быть бесконечным циклом, что приводит к тому, что работа программы запускается снова и снова.
Ошибка 487 Logic Error — Логическая ошибка вызывает неправильный вывод, даже если пользователь дал действительные входные данные. Это связано с ошибками в исходном коде Microsoft Corporation, обрабатывающих ввод неправильно.
Повреждение, отсутствие или удаление файлов Windows Error 487 может привести к ошибкам Windows. Возникновение подобных проблем является раздражающим фактором, однако их легко устранить, заменив файл Microsoft Corporation, из-за которого возникает проблема. Помимо прочего, в качестве общей меры по профилактике и очистке мы рекомендуем использовать очиститель реестра для очистки любых недопустимых записей файлов, расширений файлов Microsoft Corporation или разделов реестра, что позволит предотвратить появление связанных с ними сообщений об ошибках.
Распространенные проблемы Windows Error 487
Эти проблемы Windows, связанные с Windows Error 487, включают в себя:
- «Ошибка приложения Windows Error 487.»
- «Недопустимый файл Windows Error 487. «
- «Извините, Windows Error 487 столкнулся с проблемой. «
- «Не удается найти Windows Error 487»
- «Windows Error 487 не найден.»
- «Ошибка запуска программы: Windows Error 487.»
- «Файл Windows Error 487 не запущен.»
- «Отказ Windows Error 487.»
- «Неверный путь к программе: Windows Error 487. «
Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Windows Error 487 (например, Windows) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. Запись ошибок Windows Error 487 внутри Windows имеет решающее значение для обнаружения неисправностей электронной Windows и ретрансляции обратно в Microsoft Corporation для параметров ремонта.
Создатели Windows Error 487 Трудности
Проблемы Windows Error 487 вызваны поврежденным или отсутствующим Windows Error 487, недопустимыми ключами реестра, связанными с Windows, или вредоносным ПО.
Более конкретно, данные ошибки Windows Error 487 могут быть вызваны следующими причинами:
- Недопустимый Windows Error 487 или поврежденный раздел реестра.
- Зазаражение вредоносными программами повредил файл Windows Error 487.
- Вредоносное удаление (или ошибка) Windows Error 487 другим приложением (не Windows).
- Другое программное обеспечение, конфликтующее с Windows, Windows Error 487 или общими ссылками.
- Windows/Windows Error 487 поврежден от неполной загрузки или установки.
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
How to fix the Runtime Code 487 Windows Error 487
This article features error number Code 487, commonly known as Windows Error 487 described as Error 487: Windows has encountered a problem and needs to close. We are sorry for the inconvenience.
About Runtime Code 487
Runtime Code 487 happens when Windows fails or crashes whilst it’s running, hence its name. It doesn’t necessarily mean that the code was corrupt in some way, but just that it did not work during its run-time. This kind of error will appear as an annoying notification on your screen unless handled and corrected. Here are symptoms, causes and ways to troubleshoot the problem.
Definitions (Beta)
Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!
- Windows — GENERAL WINDOWS SUPPORT IS OFF-TOPIC
Symptoms of Code 487 — Windows Error 487
Runtime errors happen without warning. The error message can come up the screen anytime Windows is run. In fact, the error message or some other dialogue box can come up again and again if not addressed early on.
There may be instances of files deletion or new files appearing. Though this symptom is largely due to virus infection, it can be attributed as a symptom for runtime error, as virus infection is one of the causes for runtime error. User may also experience a sudden drop in internet connection speed, yet again, this is not always the case.
(For illustrative purposes only)
Causes of Windows Error 487 — Code 487
During software design, programmers code anticipating the occurrence of errors. However, there are no perfect designs, as errors can be expected even with the best program design. Glitches can happen during runtime if a certain error is not experienced and addressed during design and testing.
Runtime errors are generally caused by incompatible programs running at the same time. It may also occur because of memory problem, a bad graphics driver or virus infection. Whatever the case may be, the problem must be resolved immediately to avoid further problems. Here are ways to remedy the error.
Repair Methods
Runtime errors may be annoying and persistent, but it is not totally hopeless, repairs are available. Here are ways to do it.
If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.
Please note: Neither ErrorVault.com nor it’s writers claim responsibility for the results of the actions taken from employing any of the repair methods listed on this page — you complete these steps at your own risk.
Method 1 — Close Conflicting Programs
When you get a runtime error, keep in mind that it is happening due to programs that are conflicting with each other. The first thing you can do to resolve the problem is to stop these conflicting programs.
- Open Task Manager by clicking Ctrl-Alt-Del at the same time. This will let you see the list of programs currently running.
- Go to the Processes tab and stop the programs one by one by highlighting each program and clicking the End Process buttom.
- You will need to observe if the error message will reoccur each time you stop a process.
- Once you get to identify which program is causing the error, you may go ahead with the next troubleshooting step, reinstalling the application.
Method 2 — Update / Reinstall Conflicting Programs
Using Control Panel
- For Windows 7, click the Start Button, then click Control panel, then Uninstall a program
- For Windows 8, click the Start Button, then scroll down and click More Settings, then click Control panel > Uninstall a program.
- For Windows 10, just type Control Panel on the search box and click the result, then click Uninstall a program
- Once inside Programs and Features, click the problem program and click Update or Uninstall.
- If you chose to update, then you will just need to follow the prompt to complete the process, however if you chose to Uninstall, you will follow the prompt to uninstall and then re-download or use the application’s installation disk to reinstall the program.
Using Other Methods
- For Windows 7, you may find the list of all installed programs when you click Start and scroll your mouse over the list that appear on the tab. You may see on that list utility for uninstalling the program. You may go ahead and uninstall using utilities available in this tab.
- For Windows 10, you may click Start, then Settings, then choose Apps.
- Scroll down to see the list of Apps and features installed in your computer.
- Click the Program which is causing the runtime error, then you may choose to uninstall or click Advanced options to reset the application.
Method 3 — Update your Virus protection program or download and install the latest Windows Update
Virus infection causing runtime error on your computer must immediately be prevented, quarantined or deleted. Make sure you update your virus program and run a thorough scan of the computer or, run Windows update so you can get the latest virus definition and fix.
Method 4 — Re-install Runtime Libraries
You might be getting the error because of an update, like the MS Visual C++ package which might not be installed properly or completely. What you can do then is to uninstall the current package and install a fresh copy.
- Uninstall the package by going to Programs and Features, find and highlight the Microsoft Visual C++ Redistributable Package.
- Click Uninstall on top of the list, and when it is done, reboot your computer.
- Download the latest redistributable package from Microsoft then install it.
Method 5 — Run Disk Cleanup
You might also be experiencing runtime error because of a very low free space on your computer.
- You should consider backing up your files and freeing up space on your hard drive
- You can also clear your cache and reboot your computer
- You can also run Disk Cleanup, open your explorer window and right click your main directory (this is usually C: )
- Click Properties and then click Disk Cleanup
Method 6 — Reinstall Your Graphics Driver
If the error is related to a bad graphics driver, then you may do the following:
- Open your Device Manager, locate the graphics driver
- Right click the video card driver then click uninstall, then restart your computer
Method 7 — IE related Runtime Error
If the error you are getting is related to the Internet Explorer, you may do the following:
- Reset your browser.
- For Windows 7, you may click Start, go to Control Panel, then click Internet Options on the left side. Then you can click Advanced tab then click the Reset button.
- For Windows 8 and 10, you may click search and type Internet Options, then go to Advanced tab and click Reset.
- Disable script debugging and error notifications.
- On the same Internet Options window, you may go to Advanced tab and look for Disable script debugging
- Put a check mark on the radio button
- At the same time, uncheck the «Display a Notification about every Script Error» item and then click Apply and OK, then reboot your computer.
If these quick fixes do not work, you can always backup files and run repair reinstall on your computer. However, you can do that later when the solutions listed here did not do the job.
Other languages:
Wie beheben Fehler 487 (Windows-Fehler 487) — Fehler 487: Windows hat ein Problem festgestellt und muss geschlossen werden. Wir entschuldigen uns für die Unannehmlichkeiten.
Come fissare Errore 487 (Errore di Windows 487) — Errore 487: Windows ha riscontrato un problema e deve essere chiuso. Ci scusiamo per l’inconveniente.
Hoe maak je Fout 487 (Windows-fout 487) — Fout 487: Windows heeft een probleem ondervonden en moet worden afgesloten. Excuses voor het ongemak.
Comment réparer Erreur 487 (Erreur Windows 487) — Erreur 487 : Windows a rencontré un problème et doit se fermer. Nous sommes désolés du dérangement.
어떻게 고치는 지 오류 487 (윈도우 오류 487) — 오류 487: Windows에 문제가 발생해 닫아야 합니다. 불편을 끼쳐드려 죄송합니다.
Como corrigir o Erro 487 (Erro 487 do Windows) — Erro 487: O Windows encontrou um problema e precisa fechar. Lamentamos o inconveniente.
Hur man åtgärdar Fel 487 (Windows fel 487) — Fel 487: Windows har stött på ett problem och måste avslutas. Vi är ledsna för besväret.
Как исправить Ошибка 487 (Ошибка Windows 487) — Ошибка 487: Возникла ошибка в приложении Windows. Приложение будет закрыто. Приносим свои извинения за неудобства.
Jak naprawić Błąd 487 (Błąd systemu Windows 487) — Błąd 487: system Windows napotkał problem i musi zostać zamknięty. Przepraszamy za niedogodności.
Cómo arreglar Error 487 (Error 487 de Windows) — Error 487: Windows ha detectado un problema y debe cerrarse. Lamentamos las molestias.
About The Author: Phil Hart has been a Microsoft Community Contributor since 2010. With a current point score over 100,000, they’ve contributed more than 3000 answers in the Microsoft Support forums and have created almost 200 new help articles in the Technet Wiki.
Follow Us:
Recommended Repair Tool:
This repair tool can fix common computer problems such as blue screens, crashes and freezes, missing DLL files, as well as repair malware/virus damage and more by replacing damaged and missing system files.
STEP 1:
Click Here to Download and install the Windows repair tool.
STEP 2:
Click on Start Scan and let it analyze your device.
STEP 3:
Click on Repair All to fix all of the issues it detected.
DOWNLOAD NOW
Compatibility
Requirements
1 Ghz CPU, 512 MB RAM, 40 GB HDD
This download offers unlimited scans of your Windows PC for free. Full system repairs start at $19.95.
Article ID: ACX012724EN
Applies To: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000
Speed Up Tip #42
Browse Faster with an Ad Blocker:
Easily remove obtrusive and annoying ads by using an ad-blocking plugin. It can seamlessly integrate into your browser. Aside from speeding-up your browsing experience, it can also save you from being forced to watch a video ad or listen to an auto-playing audio pitch.
Click Here for another way to speed up your Windows PC
i what to hook this : Ordinal 4356
.text:000000018042263C ; =============== S U B R O U T I N E
.text:000000018042263C
.text:000000018042263C
.text:000000018042263C public MSO_4356
.text:000000018042263C MSO_4356 proc near ; CODE XREF: sub_180421EF8+291↑p
.text:000000018042263C ; sub_180421EF8+3D4↑p …
.text:000000018042263C jmp short loc_180422640
.text:000000018042263C ; —————————————————————————
.text:000000018042263E align 20h
.text:0000000180422640
.text:0000000180422640 loc_180422640: ; CODE XREF: MSO_4356↑j
.text:0000000180422640 jmp short sub_180422644
.text:0000000180422640 MSO_4356 endp
.text:0000000180422640
.text:0000000180422640 ; —————————————————————————
.text:0000000180422642 align 4
.text:0000000180422644
.text:0000000180422644 ; =============== S U B R O U T I N E =======================================
.text:0000000180422644
.text:0000000180422644
.text:0000000180422644 sub_180422644 proc near ; CODE XREF: MSO_4356:loc_180422640↑j
.text:0000000180422644 ; DATA XREF: .pdata:00000001815CAB84↓o
.text:0000000180422644
.text:0000000180422644 arg_0 = qword ptr 8
.text:0000000180422644
.text:0000000180422644 mov [rsp+arg_0], rbx
.text:0000000180422649 push rdi
.text:000000018042264A sub rsp, 20h
.text:000000018042264E movsxd rbx, ecx
.text:0000000180422651 mov rdi, rdx
.text:0000000180422654 mov ecx, ebx
.text:0000000180422656 call sub_180420DC0
.text:000000018042265B test eax, eax
.text:000000018042265D js short loc_180422681
.text:000000018042265F mov rdx, rdi
.text:0000000180422662 mov ecx, ebx
.text:0000000180422664 call sub_1804224D0
.text:0000000180422669 test eax, eax
.text:000000018042266B js short loc_180422681
.text:000000018042266D lea rcx, qword_18159EC20
.text:0000000180422674 mov rdx, rdi
.text:0000000180422677 mov rcx, [rcx+rbx*8]
.text:000000018042267B mov rax, [rcx]
.text:000000018042267E call qword ptr [rax+10h]
.text:0000000180422681
.text:0000000180422681 loc_180422681: ; CODE XREF: sub_180422644+19↑j
.text:0000000180422681 ; sub_180422644+27↑j
.text:0000000180422681 mov rbx, [rsp+28h+arg_0]
.text:0000000180422686 add rsp, 20h
.text:000000018042268A pop rdi
.text:000000018042268B retn
.text:000000018042268B sub_180422644 endp
.text:000000018042268B
.text:000000018042268C
My guess from your code is that you’re trying to load a DLL or EXE into memory manually using something like this technique — is that right? I’ll address this at the end (pun intended) but first a quick explanation of why VirtualAllocEx
is failing.
Why is VirtualAllocEx
giving this error?
The problem with allocating memory at a specific address is that there needs to be enough room at that address to allocate the memory size you request. This is why, generally, when you request memory you let the OS decide where to put it. (Plus letting the OS / malloc library decide can lead to other benefits, such as decreased fragmentation etc — out of scope for this answer.)
The problem you’re getting is not that VirtualAllocEx
is incapable of allocating 64MB rather than 4MB. VirtualAllocEx
can allocate (nearly) as much memory as you want it to. The problem is that at the address you specify, in your process, there isn’t 64MB of unallocated memory.
Consider hypothetical addresses 0-15 (0x0 — 0xF), where -
marks empty memory and x
marks allocated memory:
0 1 2 3 4 5 6 7 8 9 A B C D E F
x x - x - - - - x - - - - - - -
This is your process’s memory space. Now, you want to allocate 4 bytes at address 0x4. Easy — 0x4 to 0x7 are free, so you allocate and get (new allocation marked with X):
0 1 2 3 4 5 6 7 8 9 A B C D E F
x x - x X X X X x - - - - - - -
Fantastic. But now suppose that instead you wanted to allocate 6 bytes. There aren’t six free bytes at address 0x4: there’s some memory being used at 0x8:
0 1 2 3 4 5 6 7 8 9 A B C D E F
x x - x - - - - x - - - - - - -
1 2 3 4 bang!
You can’t do it. The problem isn’t that the memory allocator can’t handle allocating 6 bytes, but that the memory isn’t free for it to do it. Nor, most likely, can it shuffle the memory around — in a normal non-GC program you can’t move memory to make space, because you might, say, leave dangling pointers which don’t know the contents of the memory they were pointing at has changed address. The only thing to do is either fail and not allocate memory at all, or allocate where it has free space, say at 0x9 or 0xA.
You might wonder why VirtualAllocEx
is failing with ERROR_INVALID_ADDRESS
instead of NULL
: most likely, it is because you specified an address it couldn’t allocate at; thus, even though there is some free memory at that address (maybe) there isn’t enough and the address isn’t valid. This is hinted at in the documentation:
Attempting to commit a specific address range by specifying MEM_COMMIT
without MEM_RESERVE and a non-NULL lpAddress fails unless the entire
range has already been reserved. The resulting error code is
ERROR_INVALID_ADDRESS.
This isn’t quite your situation: you’re specifying both flags at once, but if the method can’t reserve then it effectively falls into this situation. It can’t reserve the entire range at that address, so it gives error code ERROR_INVALID_ADDRESS
.
Loading DLL or EXE images
So, what should you do with your problem, which I am guessing from your question and code is loading a DLL or EXE image in memory?
Here you need a bit of background on image locations in an EXE file. Generally, an EXE is loaded into memory at the process’s virtual address location 0x400000. It’s optional: your linker can ask it be put wherever, but this value is common. Similarly, DLLs have a common default location: 0x10000000. So, for one EXE and one DLL, you’re fine: the image loader can almost certainly load them at their requested locations.
What happens when you have two DLLs, both asking to be located at 0x10000000?
The answer is image rebasing. The image location is optional, it’s not necessary. Code inside the image that depends on being loaded at a specific address can be adjusted by the image loader, and so the second DLL might be loaded not at 0x10000000, but somewhere else — say, 0x1080000. That’s an address difference of 0x80000, and so the loader actually patches up a bunch of addresses and code inside the DLL so all the bits that thought they should refer to 0x10000000 now refer to 0x10800000.
This is really, really common, and every time you load an EXE this will be done to several DLLs. It is so common that Microsoft have a little optimisation tool called rebase, (for «rebasing», that is, adjusting the base address) and when you distribute your EXE and your own DLLs with it, you can use this to make sure each DLL has a different base address, each of which is located so that when Windows loads your EXE and the DLLs they will already have the right addresses and it is unlikely to have to rebase — perform the above operation — on any of them. For some applications this can make a noticeable improvement in starting time. (In modern versions of Windows, sometimes DLLs are moved around anyway — this is for address space layout randomization, a security technique to deliberately make sure code is not at the same address each time it’s run.)
(One other thing is that some DLL and EXE compression tools strip out the data that is used for this relocation. That’s fine, because it makes the EXE smaller… right up until it needs to be relocated, and because the data is missing it can’t, and so can’t be loaded at all. Or you can build with a fixed base, and it will magically work right until it doesn’t. Don’t do this to your EXEs or DLLs.)
So, what should you do when you try to manually load a DLL into memory, and there isn’t enough space for it at the address it asks to be loaded at? Easy — it’s not a fatal error, just load it somewhere else, and then perform the rebasing yourself. I would suggest if you have problems to ask a new SO question, but to give you a starting point you can use the RebaseImage
function, or if you can’t use it or want to do it yourself, I found this code which from a quick overview seems to perform this manually. No guarantees about its correctness.
TLDR
Your process address space doesn’t have 64MB of empty space at the address you specify, so you can’t allocate 64MB of memory there. Instead, allocate it somewhere else and patch / rebase your loaded DLL or EXE image to match the new address.
I am developing multi-process applications on Windows 2012 R2 64bit.
In this application, one parent process invokes multiple child processes, and these execution modules are the same.
Also, by using a memory-mapped file to share memory, the parent process communicates with the child process.
In order to share memory, these processes need to place memory at the same virtual address.
For that, we follow the following procedure.
1. The parent calls CreateFileMapping (INVALID_HANDLE_VALUE, PAGE_READWRITE) to create a memory mapped file.
2. The parent calls CreateProcess (CREATE_SUSPENDED) and starts the child in the suspended state.
3. The child releases the area reserved by the parent with VirtualFree (MEM_RELEASE).
4. The child calls MapViewOfFileEx (FILE_MAP_READ | FILE_MAP_WRITE) immediately after 3. and initializes the local memory pointer to reference the shared memory.
5. The parent calls VirtualAllocEx (MEM_RESERVE, PAGE_READWRITE) and reserves the address range to allocate shared memory in the child’s address space.
6. The parent calls ResumeThread () and resume execution of the child.
The problem is that VirtualAllocEx (MEM_RESERVE, PAGE_READWRITE) has failed with system error code 487.
Since I reserved the address space after starting the child process in the suspended state, I think that it has not been used already.
Reproducibility of this phenomenon is not high, and occasionally occurs.
Also, only specific users are experiencing.
The characteristic of the environment is that the number of processes is large(larger 40 processes), and the OS runs on XEN in a virtual environment.
I thought about the effect of ASLR, but since this application is built with / DYNAMICBASE: NO set, it will not be affected by ASLR.
Please tell me the cause of this problem.
Also, please tell me how to prevent the reserved address range from being used.
Позвольте мне уточнить, этот код работает на 100% на Windows Vista и Windows 7, однако функция VirtualProtectEx
не удается на Windows XP с GetLastError()
код 487 — ERROR_INVALID_ADDRESS.
Вот связанная функция:
int HpRemoteHookInstall(__in HANDLE m_hProcess, __in LPVOID m_pvTargetAddress, __in LPVOID m_pvRedirectAddress) {
// Misc checks
if ( m_pvTargetAddress == NULL || m_pvRedirectAddress == NULL )
{
return -1;
}
DWORD m_dwOldRights = NULL;
BYTE m_btHotPatch[7];
ZeroMemory(m_btHotPatch, sizeof(m_btHotPatch));
// m_hProcess - remote process
// m_pvTargetAddress - remote base
// Allow write access - code will be restored later on
if ( VirtualProtectEx(m_hProcess, (LPVOID)m_pvTargetAddress, 6, PAGE_EXECUTE_READWRITE, &m_dwOldRights) == FALSE )
{
DisplayError(); // displays getlasterror function in messagebox
return -2;
}
Что я мог делать не так?
Спасибо за ваше время.
редактировать — Значение m_pvTargetAddress является постоянным в каждой операционной системе (что означает то же самое при каждом выполнении), но отличается между тремя ОС
редактировать — Я получаю m_pvTargetAddress через GetThreadContex (Удаленный поток) -> Eip контекста
редактировать — Вот значения VirtualQueryEx, возвращаемые при вызове:
Windows XP
- 0 — база размещения
- 0 — распределение защиты
- 2088828928 — базовый адрес
- 1 — защитить
- 983040 — размер региона
- 65536 — состояние
- 0 — тип
Windows 7
- 2003959808 — база распределения
- 128 — распределение защиты
- 2004025344 — базовый адрес
- 32 — защита
- 876544 — размер региона
- 4096 — состояние
- 16777216 — тип
Виндоус виста
- 2006122496 — база размещения
- 128 — распределение защиты
- 2006536192 — Базовый адрес
- 32 — защита
- 389120 — размер региона
- 4096 — состояние
- 16777216 — тип
1
Решение
Я бы предложил вам распечатать m_pvTargetAddress
значение и проверьте, является ли это действительным адресом в целевом адресном пространстве, например, отладчик или ProcessExplorer и т. д., или вызов VirtualQueryEx
запросить, является ли адрес действительным до VirtualProtectEx
называется. еще одна вещь, чтобы проверить, как следует цитата из MSDN:
Все страницы в указанном регионе должны быть в пределах одного зарезервированного
регион, выделенный при вызове VirtualAlloc или VirtualAllocEx
функция с использованием MEM_RESERVE. Страницы не могут занимать смежные зарезервированные
регионы, которые были выделены отдельными вызовами в VirtualAlloc или
VirtualAllocEx, используя MEM_RESERVE.
1
Другие решения
Других решений пока нет …
- Remove From My Forums
-
Question
-
Hi!
We are calling to a regular phone where no one answers. After approx. 15-20 secs the call gets hanged up by Lync Server with the error message «487 Request Cancelled». Why?
/Andreas
All replies
-
You may want to take a look at this command
http://technet.microsoft.com/en-us/library/gg398238.aspxto set Set-CsTrunkConfiguration -RTCPActiveCalls $false -RTCPCallsOnHold $false
Regards Herbert Zimbizi
Thank you for your answer. I tried your solution, but it didn’t solve the problem.
-
Hi,Andreas,
Would you please elaborate on your Lync deployment scenario?
Which gateway did you use for incoming/outgoing PSTN call?
Would you please also check your gateway to see if there are any error logs?
487 error means there is a timeout for finding correct path to route the call,please check your route setting in Lync and Gateway configuration.
Btw,did you restart Lync mediation server or related services after running
Set-CsTrunkConfiguration?Regards,
Sharon
Sharon Shen
TechNet Community Support
******************************************************************************************************************************************************* Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark
as Answer” if a marked post does not actually answer your question. This can be beneficial to other community memb-
Edited by
Friday, January 20, 2012 7:12 AM
-
Edited by
-
Hi Sharon,
Thank you for your answer! In what way does it mean «timeout for finding correct path to route the call»? There is an active call with voice and no other problems with calling or voiceflow? If someone answers it works perfectly?
I did not restart the Lync mediation server, I will do that in the weekend and come back to you on monday!
Thank you
Andreas
-
Hi,Andreas,
Sorry for responsing you so late due to holiday.
What I mean is that the request can not be transmited to the gateway in a valid time,then Lync mediation server will send a cancel request after time is out,maybe there is a route misconfiguration for PSTN call or timeout setting too short
for responsing the request.You can read through the old thread below,hope it can give you some clews.
http://social.technet.microsoft.com/Forums/en-US/ocsedge/thread/d0da1b13-87ed-4698-bfa4-fea21781972e/
Regards,
Sharon
Sharon Shen
TechNet Community Support
******************************************************************************************************************************************************* Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if
a marked post does not actually answer your question. This can be beneficial to other community memb
К нам часто обращаются с похожим вопросом: по какому принципу происходит переключение транка в исходящем правиле, если основной транк недоступен?
Мы подготовили исчерпывающий ответ на этот вопрос. Его можно разделить на 3 части:
- Выбор и переключение маршрута / транка в исходящем правиле
- Особенности обработки сообщений Early Media и Ringing
- Особенности транков с авторизацией по IP (пиринговые транки без регистрации)
Введение
Как известно, 3CX может иметь до 5 разных маршрутов в исходящем правиле. Вы можете определить приоритет этих маршрутов. Если первый маршрут (по сути дела, транк или VoIP шлюз) не может проключить вызов, он передается по второму маршруту и т.д.
Нам важно понимать, какие именно события могут влиять на отказ в проключении вызова по основному транку и переключении на резервный транк.
Выбор и переключение маршрута
- В исходящем правиле 3CX опрашивает все доступные транки и мосты (межстанционные транки) по порядку от 1 до 5
- Если транк не зарегистрирован, он исключается автоматически
- SIP сообщение Ringing (180 или 183) от оператора связи (или VoIP шлюза) не означает успешное проключение. Может быть выбран другой транк, либо перебор транков может завершиться в зависимости от полученных SIP сообщений в дальнейшем (см. ниже)
- SIP сообщение Busy завершает перебор транков и передает сигнал “занято” вызывающему абоненту. Типы SIP сообщений Busy:
- 486 Busy Here — абонент занят
- 600 Busy Everywhere — вызываемый пользователь занят и не желает принимать вызов в данный момент
- 1408 No Response — внутренний код ошибки 3CX
- SIP сообщение об успешном проключении завершает перебор транков. Типы сообщений об успешном проключении:
- 200 OK — успешное завершение проключения
- Cancel — вызываемый абонент отклонил вызов, не подняв трубку
- SIP сообщение об ошибке проключения начинает перебор транков (выбор следующего транка по приоритету). Список SIP сообщений об ошибках приведен в конце этой инструкции.
Параметры Early Media и Ringing
При использовании в исходящем правиле более одного транка, обработка сообщений Early Media и Ringing имеет свои особенности. Поскольку 3CX не может предсказать заранее, произойдет ли переключение на резервный маршрут, она меняет правила обработки сообщений Early media (как правило, 183 Ringing).
После получения SIP сообщения 183 Ringing, которые обычно используются при передаче специфических сообщений от оператора (например, служебных голосовых сообщений сети типа “ожидайте ответа абонента”), это сообщение конвертируется в SIP сообщение 180, и аудиопоток от оператора “заглушается”. Абонент на добавочном номере 3CX слышит не служебные сообщения оператора, а гудки дозвона SIP телефона (КПВ). Для справки:
- 180 Ringing — местоположение вызываемого пользователя определено, выдан сигнал о входящем вызове
- 183 Session Progress — используется для того, чтобы заранее получить описание сеанса информационного обмена от шлюзов на пути к вызываемому пользователю
Транки с IP авторизацией
Если оператор предоставил транк для сервера 3CX на публичный IP адрес этого сервера (транк с IP авторизацией), 3CX не регистрирует транк на SIP сервере оператора. Таким образом, 3CX не может определить, “работает” этот транк или нет. С точки зрения 3CX он всегда “работает” (в 3CX “светится” зеленым цветом). При обработке исходящего правила 3CX всегда будет пытаться использовать этот транк. Если транк “нерабочий”, это приведет к задержке 32 сек. перед переключением на следующий транк. К сожалению, это поведение нельзя изменить.
Коды SIP ошибок переключения транка
Коды SIP сообщений (ошибок), при котором происходит переключение транка:
- 400 Bad Request — запрос не понят из-за синтаксических ошибок в нем; ошибка в сигнализации, скорее всего что-то с настройками оборудования
- 401 Unauthorized — нормальный ответ сервера о том, что пользователь еще не авторизировался; обычно после этого абонентское оборудование отправляет на сервер новый запрос, содержащий логин и пароль
- 402 Payment Required — требуется оплата
- 403 Forbidden — абонент не зарегистрирован
- 404 Not Found — вызываемый абонент не найден; нет такого SIP-номера
- 405 Method Not Allowed — метод не поддерживается; может возникать, если пользователь пытается отправлять голосовую почту и т.п.
- 406 Not Acceptable — пользователь недоступен
- 407 Proxy Authentication Required — необходима аутентификация на прокси-сервере
- 408 Request Timeout — время обработки запроса истекло; абонента не удалось найти за отведенное время
- 409 Conflict — конфликт
- 410 Gone — нет доступа к ресурсу; ресурс по указанному адресу больше не существует
- 411 Length Required — для указанного ресурса клиент должен указать длину содержимого в заголовке запроса
- 413 Request Entity too large — размер запроса слишком велик для обработки на сервере
- 414 Request URI too long — размер SIP URI слишком велик для обработки на сервере
- 415 Unsupported Media Type — звонок совершается неподдерживаемым кодеком
- 416 Unsupported URI Scheme — сервер не может обработать запрос из-за того, что схема адреса получателя ему непонятна
- 420 Bad Extension — неизвестное расширение; сервер не понял расширение протокола SIP
- 421 Extension Required — в заголовке запроса не указано, какое расширение сервер должен применить для его обработки
- 423 Interval too brief — сервер отклоняет запрос, так как время действия ресурса слишком короткое
- 433 Anonymity Disallowed — анонимный вызов запрещен
- 480 Temp Unavailable — временно недоступное направление, попробуйте позвонить позже
- 481 Call Transaction does not exist — действие не выполнено; нормальный ответ при поступлении дублирующего пакета
- 482 Loop Detected — обнаружен замкнутый маршрут передачи запроса
- 483 Too many hops — запрос на своем пути прошел через большее число прокси-серверов, чем разрешено
- 484 Address Incomplete — принят запрос с неполным адресом
- 485 Ambiguos — адрес вызываемого пользователя неоднозначен
- 487 Request Terminated — запрос отменен; обычно приходит при отмене вызова
- 500 Server Internal Error — внутренняя ошибка сервера
- 501 Not Implemented — в сервере не реализованы какие-либо функции, необходимые для обслуживания запроса; метод запроса SIP не поддерживается
- 502 Bad Gateway — сервер, функционирующий в качестве шлюза или прокси-сервера, принимает некорректный ответ от сервера, к которому он направил запрос
- 503 Service Unavailable — сервер не может в данный момент обслужить вызов из-за перегрузки или проведения технического обслуживания
- 504 Server Timeout — сервер не получил ответа в течение установленного промежутка времени от сервера, к которому он обратился для завершения вызова
- 505 Version Not Supported — версия не поддерживается; сервер не поддерживает эту версию протокола SIP
- 513 Message Too Large — сервер не в состоянии обработать запрос из-за большой длины сообщения
- 603 Decline — вызываемый пользователь не желает принимать входящие вызовы, не указывая причину отказа
- 604 Does not exist anywhere — вызываемого пользователя не существует
- 606 Not Acceptable — соединение с сервером было установлено, но отдельные параметры, такие как тип запрашиваемой информации, полоса пропускания или вид адресации недоступны
Softphone.Pro — это SIP клиент, в котором вы настроили SIP учетную запись вашей АТС. Другими словами, для приёма и совершения звонков софтфон общается с вашей АТС. В процессе общения софтфон может получать от вашей АТС ответы, содержащие определенные коды ошибок. Технические специалисты легко ориентируются в кодах ошибок и знают, как их исправить, но для обычного пользователя эти ошибки непонятны.
Ниже мы описали распространенные коды ошибок, исправить которые вам может помочь ваш технический специалист или специалисты из поддержки вашей АТС. Увидев данные коды ошибок, вы можете сразу обратиться в поддержку вашей АТС или к вашему системному администратору.
401 Unauthorized
401 Unauthorized это код ошибки авторизации. Она может быть вызвана некорректными данными SIP учётной записи (адреса сервреа, логина, пароля и т.п.). Для устранения ошибки иногда достаточно перепроверить введённые данные SIP учётной записи, полученные от вашего провайдера телефонии, и исправить опечатки.
По нашему опыту, самая частая причина возникновения данной ошибки это неверные данные SIP учётной записи. Другой причиной получения данной ошибки от провайдера может быть попытка зарегистрировать SIP учётную запись на нескольких устройствах одновременно, так как сервер может отклонять множественные попытки регистрации. Тем не менее, точную причину возникновения данной ошибки знают администратор вашей АТС или провайдер телефонии, пожалуйста обратитесь к ним за помощью в устранении ошибки.
402 Payment Required
Данная ошибка может возникать из-за проблем c оплатой: например, недостаточно средств в личном кабинете вашей АТС, отключены услуги, необходимые для совершения звонков или работы АТС, и т.д.
Ошибка SIP 402 Payment Required не связана с оплатой самого Softphone.Pro. Если оплаченный период закончится, вы увидите другое уведомление в интерфейсе софтфона: «Срок действия лицензионного ключа истек».
Пожалуйста, свяжитесь с вашим администратором АТС или провайдером телефонии, чтобы выяснить причину возникновения данной ошибки.
403 Forbidden
Самые распространённые причины возникновения ошибки 403 Forbidden:
- Неправильные данные SIP учётной записи;
- Требуемые имя пользователя и пароль не предоставлены;
- Неправильный префикс для международных звонков;
- Одновременные попытки регистрации с разных устройств;
- SIP учётная запись могла быть удалена или заблокирована на вашей АТС.
Помочь с корректными настройками SIP учётной записи может поддержка вашей АТС.
404 Not Found
Вы увидите ошибку 404 Not Found, если не был получен ответ с другой стороны при запросе на вашу АТС.
В первую очередь стоит проверить, правильно ли введён номер назначения. Также причина может быть в том, что вы пытаетесь совершить звонок с неверным префиксом: некоторые АТС не позволяют совершать звонки если номер начинается с + или другого спецсимвола. Помимо этого, могут быть ошибки с настройками на другой стороне или абонент сейчас недоступен: отключен, перегружен или находится на обслуживании. Уточните у вашего администратора АТС или провайдера телефонии, что может вызывать данную ошибку.
407 Proxy Authentication Required
Ошибка 407 Proxy Authentication Required возникает, когда между клиентом и сервером также расположен прокси-сервер. Другими словами, прокси не может авторизовать клиента, поэтому он не может корректно обработать запрос.
К сожалению, универсальное решение этой проблемы описать не получится, так как потенциальных причин возникновения ошибки несколько, и может быть трудно определить конкретную. Однако вы можете попытаться выполнить определённые действия на своей стороне.
В первую очередь проверьте SIP настройки, опечатки могут вызвать данную ошибку. Если ошибка не устранена, проверьте настройки сервера, просмотрите логи и скрипты на предмет ошибок. Пожалуйста, обратитесь к ответственному администратору за помощью.
408 Request Timeout
Ошибку 408 Request Timeout вы увидите, если софтфон не получает ответ от сервера ответ или отсутствует сетевое соединение. Самая частая причина такого поведения — сменились настройки сети или некорректно заданы настройки SIP учётной записи. Ещё одна возможная причина данной ошибки — блокировка трафика (см. ниже).
Как проверить, есть ли проблемы с сетевым подключением: попытайтесь открыть случайные сайты в браузере, если не получится открыть их, свяжитесь с вашим интернет провайдером для устранения неполадок. Заодно спросите, разрешены ли VoIP звонки через его сеть.
Как проверить, не вызвана ли ошибка блокированием трафика: попробуйте отключить ваш антивирус или файрвол и проверьте, повторяется ли ошибка. Если ошибка устранена, то причина именно в этом. В дальнейшем вы можете добавить приложение в исключения (пример для антивируса Касперского по ссылке).
Также есть другие возможные причины возникновения данной ошибки. Если советы выше не помогли, пожалуйста обратитесь к вашему провайдеру или администратору АТС за помощью в устранении ошибки.
480 Temporarily Unavailable
Ошибка 480 Temporarily Unavailable значит, что звонок не достиг назначения. Данная ситуация временная и скорее всего не связана с вашей АТС.
Возможные причины возникновения данной ошибки следующие. Во-первых, звонок был отклонён провайдером или конечным устройством. Во-вторых, звонок не может быть совершён из-за недоступного или незарегистрированного устройства или провайдера. В-третьих, звонок может быть отменён из-за высокой нагрузки сети.
В первом случае, пожалуйста, свяжитесь с вашим провайдером. Во втором случае, пожалуйста, проверьте устройство или статус регистрации провайдера. В случае нагрузки на сеть просто попробуйте совершить звонок повторно, есть шанс на успех.
482 Loop Detected
Ошибка 482 Loop Detected это ошибка некорректного маршрута звонка или внутренняя ошибка АТС. Лучше всего в данной ситуации проверить настройки маршрутизации на устройстве или вызвать ответственного специалиста.
487 Request Terminated
Ошибка 487 Request Terminated обычно случается, когда запрос отменён, и сервер сообщает об этом клиенту. Однако могут быть и другие возможные причины для возникновения данной ошибки, поэтому лучше всего связаться с вашим провайдером. Данная ошибка возникает не на стороне софтфона.
488 Not Acceptable Here
Ошибку 488 Not Acceptable Here вы видите, если соединение установлено, но часть параметров соединения выключены или не разрешены. Изменение настроек SIP транка скорее всего поможет исправить данную ошибку. Другое возможное решение этой ошибки — отключение настройки Шифрование медиа в настройках SIP учётной записи. Ваш провайдер телефонии или администратор АТС смогут указать на настрйоки, вызывающие данную ошибку.
500 Internal Server Error
Есть несколько возможных причин возникновения ошибки 500 Internal Server Error, и ни одна из них не связана с софтфоном, это исключительно ошибка АТС.
Например, это может быть внутренней ошибкой сервера; или не получен ответ от базы данных; или получен неправильный ответ от базы данных; или учётная запись была перемещена на удалённую систему; или неопределённая причина. Таким образом, так как причина ошибки неочевидна, лучше всего будет связаться с вашим администратором АТС.
502 Bad Gateway
Ошибкой 502 Bad Gateway система говорит, что проблема в какой-то другой сети мешает обработке запроса. Данный ответ отправляет прокси, который выступает в качестве шлюза в другую сеть. Пожалуйста, свяжитесь с ответственным за вашу сеть (например, с системным администратором). Возможно, совет не очень полезный, но лучший из возможных.
503 Service Unavailable
Причиной ошибки 503 Service Unavailable может быть отсутствие ответа от DNS сервера. Также причина может быть в файрволе или операционной системе. Наконец, данная ошибка может возникать, если сервис, который вы пытаетесь использовать, недоступен.
Возможное решение: попробуйте заменить адрес SIP сервера вашего провайдера на IP адрес сервера (указать цифры вместо букв). Если ситуация повторяется от случая к случаю без определенной закономерности, возможно проблема возникает не на вашей стороне, а на стороне провайдера.
603 Decline
Что вызвало ошибку 603 Decline: с абонентом удалось связаться, но он не может или не хочет принимать звонок, софтфон не является причиной возникновения ошибки.
Самая частая причина ошибки — абонент отклонил звонок, но также возможно что она вызвана недостатком средств в учётной записи или какой-то другой причиной. Лучше всего связаться с вашим администратором АТС или провайдером телефонии, чтобы разобраться в ситуации.
Номер ошибки: | Ошибка 487 | |
Название ошибки: | Windows Error 487 | |
Описание ошибки: | Ошибка 487: Возникла ошибка в приложении Windows. Приложение будет закрыто. Приносим извинения за неудобства. | |
Разработчик: | Microsoft Corporation | |
Программное обеспечение: | Windows | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Анализ «Windows Error 487»
«Windows Error 487» — это стандартная ошибка времени выполнения. Когда дело доходит до программного обеспечения, как Windows, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. К сожалению, иногда ошибки, такие как ошибка 487, могут быть пропущены во время этого процесса.
После первоначального выпуска пользователи Windows могут столкнуться с сообщением «Windows Error 487» во время запуска программы. Если возникает ошибка 487, разработчикам будет сообщено об этой проблеме через уведомления об ошибках, которые встроены в Windows. Затем Microsoft Corporation нужно будет исправить эти ошибки в главном исходном коде и предоставить модифицированную версию для загрузки. Если есть уведомление об обновлении Windows, это может быть решением для устранения таких проблем, как ошибка 487 и обнаруженные дополнительные проблемы.
В чем причина ошибки 487?
Сбой во время запуска Windows или во время выполнения, как правило, когда вы столкнетесь с «Windows Error 487». Вот три наиболее распространенные причины, по которым происходят ошибки во время выполнения ошибки 487:
Ошибка 487 Crash — ошибка 487 блокирует любой вход, и это может привести к сбою машины. Это происходит много, когда продукт (Windows) или компьютер не может обрабатывать уникальные входные данные.
«Windows Error 487» Утечка памяти — Ошибка 487 утечка памяти происходит и предоставляет Windows в качестве виновника, перетаскивая производительность вашего ПК. Потенциальные триггеры могут быть бесконечным циклом, что приводит к тому, что работа программы запускается снова и снова.
Ошибка 487 Logic Error — Логическая ошибка вызывает неправильный вывод, даже если пользователь дал действительные входные данные. Это связано с ошибками в исходном коде Microsoft Corporation, обрабатывающих ввод неправильно.
Повреждение, отсутствие или удаление файлов Windows Error 487 может привести к ошибкам Windows. Возникновение подобных проблем является раздражающим фактором, однако их легко устранить, заменив файл Microsoft Corporation, из-за которого возникает проблема. Помимо прочего, в качестве общей меры по профилактике и очистке мы рекомендуем использовать очиститель реестра для очистки любых недопустимых записей файлов, расширений файлов Microsoft Corporation или разделов реестра, что позволит предотвратить появление связанных с ними сообщений об ошибках.
Распространенные проблемы Windows Error 487
Эти проблемы Windows, связанные с Windows Error 487, включают в себя:
- «Ошибка приложения Windows Error 487.»
- «Недопустимый файл Windows Error 487. «
- «Извините, Windows Error 487 столкнулся с проблемой. «
- «Не удается найти Windows Error 487»
- «Windows Error 487 не найден.»
- «Ошибка запуска программы: Windows Error 487.»
- «Файл Windows Error 487 не запущен.»
- «Отказ Windows Error 487.»
- «Неверный путь к программе: Windows Error 487. «
Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Windows Error 487 (например, Windows) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. Запись ошибок Windows Error 487 внутри Windows имеет решающее значение для обнаружения неисправностей электронной Windows и ретрансляции обратно в Microsoft Corporation для параметров ремонта.
Создатели Windows Error 487 Трудности
Проблемы Windows Error 487 вызваны поврежденным или отсутствующим Windows Error 487, недопустимыми ключами реестра, связанными с Windows, или вредоносным ПО.
Более конкретно, данные ошибки Windows Error 487 могут быть вызваны следующими причинами:
- Недопустимый Windows Error 487 или поврежденный раздел реестра.
- Зазаражение вредоносными программами повредил файл Windows Error 487.
- Вредоносное удаление (или ошибка) Windows Error 487 другим приложением (не Windows).
- Другое программное обеспечение, конфликтующее с Windows, Windows Error 487 или общими ссылками.
- Windows/Windows Error 487 поврежден от неполной загрузки или установки.
Продукт Solvusoft
Загрузка
WinThruster 2023 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
Welcome to the VoIP class and today’s topic is the Sip-487 error code. We’ll learn the reasons for getting this error code and the ways for fixing the issue. Take your seat, we are starting!
What is the meaning of the SIP-487 Code?
If the caller (A side) closes the phone before connection, you’ll receive the VoIP sip code SIP-487.
The reasons for receiving the Sip-487 Code?
Sip 487 code is not an unwanted error code. Because there is no possibility for a 100% successful traffic (Except FAS, Bank numbers, IVR). Although all kinds of traffics should get this error code to a certain percentage. If this code occurs too much, it will cause to lose calls and this is an undesired situation. Because it’s impossible to connect that call again.
High PDD
The main reason for the high Sip-487 code is high PDD. Because people tend to close the phone if it takes too much to hear the dial tone. People don’t like dial tone delay. The traffics which has high PDD delay numbers then also Sip-487 Request Terminated code is high.
IVR
Another reason for the high 487 code is IVR. People are closing the phone when they hear a recorded voice and they give up calling.
Traffic Profile
Wholesale or retail, some traffic profiles have SIP-487 error codes around 80%-90%. The main reason for this is missing calls. People are calling from the expensive destinations are closing the phone before connection and then the cheaper destination is calling back to expensive ones. So 487 codes for this kind of traffic could be high.
The consequences of high SIP-487
The most crucial effect of the high Sip 487 code is high ASR and automatically this will cause loss of traffic.
How can we determine this code on monitoring?
First, you need the monitor of that traffic’s 487. A comparison between the past and now can give an idea. PDD and Sip 487 always have a direct proportion. If the PDD values are increasing then 487 is increasing as well.
If the natural 487 percentage of traffic is around 30-40% and it is rising to 60% or more, we can say that we have trouble here and we need to take action.
SIP 487 is a natural and wanted error code for healthy traffic but high Sip 487 is much more dangerous than Sip 503.
What can we do about it?
-
Control the PDD
-
If the PDD rates are above the normal for that destination than you can say that the 487 code is coming from high PDD
-
You need to determine the reason for high PDD
-
If there is no problem with PDD then you need to test the route
-
If the route is ok then you need to look for a traffic profile
Or you can take support from an expert!
Sigma Telecom is the world’s best VoIP Provider; working with the biggest operators of the world. We are the solution partner of the operators like China Mobile, Etisalat, Orange, etc. With our knowledge and great experience, we are open to your all questions.
For questions and further business opportunities, email us at business.development@sigmatelecom.com
My guess from your code is that you’re trying to load a DLL or EXE into memory manually using something like this technique — is that right? I’ll address this at the end (pun intended) but first a quick explanation of why VirtualAllocEx
is failing.
Why is VirtualAllocEx
giving this error?
The problem with allocating memory at a specific address is that there needs to be enough room at that address to allocate the memory size you request. This is why, generally, when you request memory you let the OS decide where to put it. (Plus letting the OS / malloc library decide can lead to other benefits, such as decreased fragmentation etc — out of scope for this answer.)
The problem you’re getting is not that VirtualAllocEx
is incapable of allocating 64MB rather than 4MB. VirtualAllocEx
can allocate (nearly) as much memory as you want it to. The problem is that at the address you specify, in your process, there isn’t 64MB of unallocated memory.
Consider hypothetical addresses 0-15 (0x0 — 0xF), where -
marks empty memory and x
marks allocated memory:
0 1 2 3 4 5 6 7 8 9 A B C D E F
x x - x - - - - x - - - - - - -
This is your process’s memory space. Now, you want to allocate 4 bytes at address 0x4. Easy — 0x4 to 0x7 are free, so you allocate and get (new allocation marked with X):
0 1 2 3 4 5 6 7 8 9 A B C D E F
x x - x X X X X x - - - - - - -
Fantastic. But now suppose that instead you wanted to allocate 6 bytes. There aren’t six free bytes at address 0x4: there’s some memory being used at 0x8:
0 1 2 3 4 5 6 7 8 9 A B C D E F
x x - x - - - - x - - - - - - -
1 2 3 4 bang!
You can’t do it. The problem isn’t that the memory allocator can’t handle allocating 6 bytes, but that the memory isn’t free for it to do it. Nor, most likely, can it shuffle the memory around — in a normal non-GC program you can’t move memory to make space, because you might, say, leave dangling pointers which don’t know the contents of the memory they were pointing at has changed address. The only thing to do is either fail and not allocate memory at all, or allocate where it has free space, say at 0x9 or 0xA.
You might wonder why VirtualAllocEx
is failing with ERROR_INVALID_ADDRESS
instead of NULL
: most likely, it is because you specified an address it couldn’t allocate at; thus, even though there is some free memory at that address (maybe) there isn’t enough and the address isn’t valid. This is hinted at in the documentation:
Attempting to commit a specific address range by specifying MEM_COMMIT
without MEM_RESERVE and a non-NULL lpAddress fails unless the entire
range has already been reserved. The resulting error code is
ERROR_INVALID_ADDRESS.
This isn’t quite your situation: you’re specifying both flags at once, but if the method can’t reserve then it effectively falls into this situation. It can’t reserve the entire range at that address, so it gives error code ERROR_INVALID_ADDRESS
.
Loading DLL or EXE images
So, what should you do with your problem, which I am guessing from your question and code is loading a DLL or EXE image in memory?
Here you need a bit of background on image locations in an EXE file. Generally, an EXE is loaded into memory at the process’s virtual address location 0x400000. It’s optional: your linker can ask it be put wherever, but this value is common. Similarly, DLLs have a common default location: 0x10000000. So, for one EXE and one DLL, you’re fine: the image loader can almost certainly load them at their requested locations.
What happens when you have two DLLs, both asking to be located at 0x10000000?
The answer is image rebasing. The image location is optional, it’s not necessary. Code inside the image that depends on being loaded at a specific address can be adjusted by the image loader, and so the second DLL might be loaded not at 0x10000000, but somewhere else — say, 0x1080000. That’s an address difference of 0x80000, and so the loader actually patches up a bunch of addresses and code inside the DLL so all the bits that thought they should refer to 0x10000000 now refer to 0x10800000.
This is really, really common, and every time you load an EXE this will be done to several DLLs. It is so common that Microsoft have a little optimisation tool called rebase, (for «rebasing», that is, adjusting the base address) and when you distribute your EXE and your own DLLs with it, you can use this to make sure each DLL has a different base address, each of which is located so that when Windows loads your EXE and the DLLs they will already have the right addresses and it is unlikely to have to rebase — perform the above operation — on any of them. For some applications this can make a noticeable improvement in starting time. (In modern versions of Windows, sometimes DLLs are moved around anyway — this is for address space layout randomization, a security technique to deliberately make sure code is not at the same address each time it’s run.)
(One other thing is that some DLL and EXE compression tools strip out the data that is used for this relocation. That’s fine, because it makes the EXE smaller… right up until it needs to be relocated, and because the data is missing it can’t, and so can’t be loaded at all. Or you can build with a fixed base, and it will magically work right until it doesn’t. Don’t do this to your EXEs or DLLs.)
So, what should you do when you try to manually load a DLL into memory, and there isn’t enough space for it at the address it asks to be loaded at? Easy — it’s not a fatal error, just load it somewhere else, and then perform the rebasing yourself. I would suggest if you have problems to ask a new SO question, but to give you a starting point you can use the RebaseImage
function, or if you can’t use it or want to do it yourself, I found this code which from a quick overview seems to perform this manually. No guarantees about its correctness.
TLDR
Your process address space doesn’t have 64MB of empty space at the address you specify, so you can’t allocate 64MB of memory there. Instead, allocate it somewhere else and patch / rebase your loaded DLL or EXE image to match the new address.