Главная » Просмотр файлов » Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU

Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891), страница 86

Файл №779891 Wiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (Symbian Books) 86 страницаWiley.Symbian.OS.Internals.Real.time.Kernel.Programming.Dec.2005.eBook-DDU (779891) страница 862018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 86)

If decompressionisn’t needed, then no special scheme is required to transfer the codein supervisor mode. The loader simply issues a file server read request,specifying the code load address as the target address. A media driverwill perform the transfer and this can use the kernel inter-thread copyfunction to write to the code segment.The loader then reads all the rest of the image (after the code section)from the file into a temporary image buffer in one operation, againdecompressing if necessary.Next the loader checks the header information to determine whetherthe file contains a code relocation section.

If so, the loader reads therelocation information from the image buffer and calls a function insupervisor mode to perform each of the relocations on the code sectionjust loaded. (This essentially involves the loader calculating the differencebetween the code run address provided by the kernel and the base addressthat the code was linked for. Then it applies this adjustment to a series of32 bit addresses obtained from the relocation section – see Section 10.1for more detail.)If the executable contains an export directory, then the loader fixesup each entry for the run address and writes it into the kernel-side codesegment, after the IAT. Again, it uses an executive function to performthis in supervisor mode.

(This is only required for PE-derived images. ELFmarks export table entries as relocations, so the loader deals with themas part of its code relocation handling.)If the executable contains an initialized data section, then the loadernow copies this from the image buffer into the code segment at the dataload address supplied (which is in fact immediately after the code, IATand export directory).If the image contains a data relocation section, then the loader appliesthese relocations in much the same way as it handled code relocations.10.3.7.3 Processing importsNext the loader must load all the DLLs referenced by this executable thatare not already loaded (rather than just those that contain static data aswas the case for XIP images). The procedure is similar to that describedfor an XIP executable.

However, with non-XIP files, the dependencyinformation is contained in the import section rather than a DLL reference410THE LOADERtable and it specifies the names of the DLLs rather than pointers to theirimage headers. Hence, for each import block, the loader has to follow theDLL search sequence described in Section 10.3.2.1. It reads each importblock from the image buffer and processes it in turn. If a dependencyneeds to be loaded from non-XIP media, the loader again has to load andrelocate its code and data sections, fix up the export tables and so on, inmuch the same way that it is loading the main executable.Once this is done, the loader now has to fix up the IAT for the mainexecutable and any dependencies that it has just loaded from non-XIPmedia.

It examines the import sections of each of these executables,which are now loaded in a series of image buffers. It processes the importblocks in turn, identifying the corresponding exporter and loading itsexport table into a buffer. Then it calls a supervisor function to fix up theentries in the IAT that correspond with this export table.Once it has processed all the dependencies, the process load requestnow continues in much the same way as it did for XIP media.For executables loaded from non-XIP media, the calling of the executive function E32Loader::CodeSegLoaded() for the new DCodeSegobjects marks the point when the loader has finished loading any datainto these segments.10.3.8 Loading a library fileThere are various overloads of the method to load a library but alleventually call:TInt RLibrary::Load(const TDesC& aFileName, const TDesC& aPath,const TUidType& aType, TUint32 aModuleVersion)The argument aFileName specifies the name of the DLL to be loaded.The descriptor aPath contains a list of path names to be searched, eachseparated by a semicolon.

The argument aType specifies a triplet of UIDswhich the DLL must match and aModuleVersion specifies the versionthat the DLL must match. As versioning was introduced for EKA2, thisfinal argument is not present in the EKA1 version of the method.This method first creates an RLoader session object and establishesa connection with the loader server.

Next it calls RLoader::LoadLibrary(), which assembles the request arguments into a messageobject and sends this to the server.On receipt of the message, the server handles the request in a similar manner to process load requests. It reads the arguments from theclient thread and searches for the specified DLL, following the sequencedescribed in Section 10.3.2.2. Then it creates a DCodeSeg object for theDLL and, if loading from non-XIP media, copies the code and initializeddata sections into this segment, performing any relocations necessary.THE LOADER SERVER411INITIAL STATEECreatedadded to processno constructors neededadded to processconstructors neededExec::LibraryAttachELoadedExec::LibraryAttachedEAttachingEAttachedlast user handle closeddestructors neededlast user handle closedno destructors neededlibraryreloadeduser-side constructorsrun while in this stateEDetachPendingExec::LibaryDetachEDetachingExec::LibraryDetacheduser-side destructors runwhile in this stateFigure 10.10 DLibrary state machineNext it processes any dependencies for the DLL and marks every newcode segment created as now being fully loaded.Next it calls the executive function, E32Loader::LibraryCreate(), which creates a DLibrary object and returns a handleto it.

See Section 10.4.4 for more details on this.Finally, the loader server writes the handle back to the client, deletesthe image objects it has created and completes the load library message.Control returns to the client thread which closes the RLoader sessionobject.If the library was loaded successfully, then the method RLibrary::Init() is called, still in the context of the client thread. This in turn callsthe executive function E32Loader::LibraryAttach() to extract thelist of entry points for the DLL and all its dependencies.

Each entry point412THE LOADERis called in turn, passing in the value KModuleEntryReasonProcessAttach as the entry reason. This runs any C++ constructor functionsfor static objects associated with these DLLs.Finally, a call of the executive function E32Loader::LibraryAttached() signals that the entry points have been completed –marking the library as being attached.

The method RLibrary::Load()now returns.Note that, in EKA2, the public DLL entry-point, E32Dll(TDllReason) is no longer invoked. This function must be present in everyEKA1 DLL, to be called when the DLL is attached to or detached from aprocess or thread. Unfortunately, this entry-point system cannot provideany guarantees that E32Dll() will be called with the appropriateparameter at the specified time.

Because it is not possible to supportthis functionality reliably, EKA2 removes support for it. This removalsimplifies the kernel-side architecture for managing dynamically loadedcode, which improves reliability and robustness.10.4Kernel-side code managementThe kernel maintains a representation of all the code resident in thesystem. The representation includes information on which modules linkto which other modules (the code graph), which processes each moduleis used by and whether a given module consists of XIP ROM-residentcode or non-XIP RAM-loaded code. The generic concepts involved areimplemented in the Symbian OS kernel, but the memory model isresponsible for the details of how memory is allocated for RAM-loadedcode, and how it is mapped into the address space of each process.The kernel and memory model only allocate memory for code storageand store information about loaded code; they do not actually load thecode.

The user-mode loader thread, described in the preceding sections,is responsible for loading images from the file system into RAM, relocatingthem to the addresses allocated by the kernel and resolving linkages toother modules prior to execution.10.4.1 Code segmentsAs we have seen, the main object involved in the management of codeis the code segment (DCodeSeg).

This represents the contents of a singleimage file (EXE or DLL) relocated for particular code and data addresses.Note that in some memory models, the kernel will create more than onecode segment from the same image file if different data section addressesare required. Of course this is expensive in terms of RAM usage, so it onlyhappens if absolutely necessary. The kernel only loads multiple copieswhere a code segment has writeable static data and is loaded into multiple processes in such a way that the data cannot be at the same address inKERNEL-SIDE CODE MANAGEMENT413all those processes. For example, on the moving memory model, a fixedprocess cannot have its data at the same address as a non-fixed process.A code segment can be created from an execute-in-place (XIP) imagefile, in which case it just contains a pointer to the TRomImageHeaderfor that file.

Характеристики

Тип файла
PDF-файл
Размер
6,63 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6367
Авторов
на СтудИзбе
309
Средний доход
с одного платного файла
Обучение Подробнее