Главная » Просмотр файлов » 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), страница 102

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

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

The tool chain will automatically link inthe appropriate library depending on the value of the ‘‘targettype’’field in the DLL’s MMP file:TargettypeLibraryDLL typeVAREVAR.LIBVariant kernel extensionKEXTEEXT.LIBKernel extensionPDDEDEV.LIBPhysical device driver DLLLDDEDEV.LIBLogical device driver DLLThe main entry point for all kernel DLLs is named _E32Dll, andits address, represented by TRomImageHeader::iEntryPoint, isobtained from the image header. This in turn invokes the DLL specific entry point _E32Dll_Body, the behavior of which depends on thetype of kernel DLL being loaded.Note: There is a fourth library, EKLL.LIB, which is imported whenspecifying the KDLL keyword for shared library DLLs. Kernel DLLs of thistype contain no static data or initialization code, so contain a simple stubentry point.Before I describe in detail how the kernel controls the initialization ofkernel DLLs are during boot, let’s take a look at how each library entrypoint handles construction and destruction of its global C++ objects.482DEVICE DRIVERS AND EXTENSIONS12.1.6.1 Construction of C++ objectsVariant extensions – EVAR.LIBSince the kernel loads the variant extension once, the variant entry pointonly constructs the DLL’s global C++ objects.

Destructors are nevercalled:GLDEF_C TInt _E32Dll_Body(TInt aReason)//// Call variant and ASIC global constructors//{if (aReason==KModuleEntryReasonVariantInit0){TUint i=1;while (__CTOR_LIST__[i])(*__CTOR_LIST__[i++])();AsicInitialise();return 0;}return KErrGeneral;}Kernel extensions – EEXT.LIBAs with the variant extension, the kernel loads an extension once duringboot, so it only constructs the DLLs global C++ objects and never callstheir destructors:GLDEF_C TInt _E32Dll_Body(TInt aReason)//// Call extension global constructors//{if (aReason==KModuleEntryReasonExtensionInit1){TUint i=1;while (__CTOR_LIST__[i])(*__CTOR_LIST__[i++])();}return KernelModuleEntry(aReason);}Device drivers – EDEV.LIBThe kernel loads and unloads device drivers dynamically, so it constructsglobal C++ objects when loading the DLL, and destroys them whenunloading it:GLDEF_C TInt _E32Dll_Body(TInt aReason)//// Call global constructors or destructors//DEVICE DRIVERS AND EXTENSIONS IN SYMBIAN OS483{if (aReason==KModuleEntryReasonProcessDetach){TUint i=1;while (__DTOR_LIST__[i])(*__DTOR_LIST__[i++])();return KErrNone;}if (aReason==KModuleEntryReasonExtensionInit1 ||aReason==KModuleEntryReasonProcessAttach){TUint i=1;while (__CTOR_LIST__[i])(*__CTOR_LIST__[i++])();}return KernelModuleEntry(aReason);}12.1.6.2 Calling entry pointsAs the previous code shows, the kernel invokes _E32Dll with a reasoncode, which it uses to control how DLLs are loaded.

Each reason code ispassed during a particular stage in the boot process.KModuleEntryReasonVariantInit0Before initializing the variant, the kernel initializes the .data sections forall kernel extensions and passes the reason code KModuleEntryReasonVariantInit0 to all extension entry points. Typically, only thevariant extension handles this reason code and, as we have already seen,this is responsible for constructing global C++ objects before invokingAsicInitialise() to initialize the ASSP.In Chapter 1, Introducing EKA2, I pointed out that the base port mightbe split into an ASSP and a variant.

Under this model, the generic ASSPclass forms a standard kernel extension that exports its constructor (at thevery least). The ASSP class must be initialized at the same time as thevariant, so it also exports the function AsicInitialise() to allow itsglobal C++ constructors to be called.After it has initialized both the variant and the ASSP extensions, thekernel obtains a pointer to the Asic derived variant specific class bycalling the variant’s first exported function:EXPORT_C Asic* VariantInitialise()This class is described in Chapter 5, Kernel Services.At the end of this process, all of the extensions’ .data sections areinitialized, and the variant and ASSP extensions are constructed and readyfor the kernel to use.484DEVICE DRIVERS AND EXTENSIONSKModuleEntryReasonExtensionInit0The kernel passes this reason code to all extension entry points that itcalls after it has started the scheduler.This reason code is an inquiry, asking whether the extension hasalready been initialized.

It allows extensions that use the KModuleEntryReasonVariantInit0 reason code to perform initialization, as Idescribed earlier. If the extension is already loaded, returning any errorcode (other than KErrNone) will prevent the next stage from beingperformed.The ASSP DLL returns KErrGeneral in response to this reason codeto report that it has already been initialized by the variant, as does thecrash monitor, which hooks into the variant initialization phase to providediagnostics of the kernel boot process.If the extension is not already loaded, the kernel will invoke its DLLentry point with the reason code KModuleEntryReasonExtensionInit1.KModuleEntryReasonExtensionInit1The kernel passes this reason code to all extension entry points afterit has verified that the extension has not already been initialized.

Thiscauses the DLL entry point to initialize global constructors before callingKernelModuleEntry to initialize the extension itself.Note that the ASSP kernel extension has already been initialized bythis point so will not receive this reason code at this point in the bootprocess.KModuleEntryReasonProcessAttach andKModuleEntryReasonProcessDetachThese reason codes are only handled by EDEV.LIB, which is specifically intended to support dynamically loadable DLLs (device drivers).KModuleEntryReasonProcessAttach is directly equivalent toKModuleEntryReasonExtensionInit1 and is used to initialize thedriver’s constructors.

Conversely, KModuleEntryReasonProcessDetach calls the driver’s destructors. These are called when the relevantcode segment is created or destroyed, as described in Chapter 10, TheLoader.12.1.7Accessing user process memoryKernel drivers and extensions need to ensure that read and write operations involving user process memory are performed safely. There aretwo scenarios to consider when servicing requests from a user process,DEVICE DRIVERS AND EXTENSIONS IN SYMBIAN OS485depending on whether the request is serviced in the context of the callingthread or a kernel thread.12.1.7.1 Servicing requests in calling thread contextRequests may be fully executed in the context of the calling threadwith supervisor-mode privileges.

Therefore, if a process passes an invalidaddress to the handler or device driver, and that address happens to bewithin the memory of another process or even the kernel itself (eitheras a result of programming error or deliberate intention), then writing tothis address could result in memory corruption and become a potentialsecurity risk.Therefore, you should never attempt to write to user memory directly,either by dereferencing a pointer or by calling a function such as memcpy.Instead, you should use<b>Текст обрезан, так как является слишком большим</b>.

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

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

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

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