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

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

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

Alternatively it can be created from a non-XIP image file;in this case the code segment owns an amount of RAM into which theloader copies the code. The kernel keeps all code segments on threeseparate lists. There is a doubly linked list (DCodeSeg::GlobalList)to which it adds code segments in order of creation. There is an arrayof pointers to DCodeSeg, sorted in lexicographic order of the rootname (DCodeSeg::CodeSegsByName). Finally there is an array ofpointers to DCodeSeg sorted in order of code run address (DCodeSeg::CodeSegsByAddress). The kernel uses the two sorted lists toallow it to perform a fast binary search for code segments by name,and to allow fast location of the code segment that contains a givenrun address (to enable C++ exception unwinding to work).

The kernelprotects these lists, and all other aspects of the global code graph, by theDCodeSeg::CodeSegLock mutex.Each code segment has an array of pointers to the other code segmentsto which it implicitly links, thus defining a global code graph (iDepCountspecifies how many other code segments this one links to, iDeps points toan array of pointers to the DCodeSeg s on which this one depends).

Thisgraph is exact for RAM-loaded code segments (that is, all code segmentsand dependencies are present) but it is reduced for XIP code segments.This reduction takes the form of transitively closing the dependencegraph, and then omitting any XIP code segments that have no .data or.bss, or are kernel extensions or variants, and are not the explicit targetof a load request. (We avoid creating code segments for these since noactual work is required to load them – the code is always visible, beingXIP, and no data initialization is required since there is either no data orit has been initialized by the kernel before the loader even started up.Effectively these DLLs are always loaded.)A code segment can have various attributes (iAttr), as follows:• ECodeSegAttKernel – this indicates that the code is intended toexecute in supervisor mode. Such code segments will be accessibleonly in privileged processor modes• ECodeSegAttGlobal – this indicates that the code should be visibleto all user processes regardless of whether they have explicitly loadedit.

Used for locales• ECodeSegAttFixed – this is only used in the moving memorymodel; it indicates that an EXE code segment is associated with a fixedprocess and so will be fixed up for a non-standard data address• ABI attribute – this is a 2-bit field indicating which ABI a code segmentconforms to. (ABI stands for Application Binary Interface and covers414THE LOADERsuch things as the calling convention used to pass parameters tofunctions and receive the return value and the manner in which objectsare laid out in memory.) Currently we define two ABIs – GCC98r2and EABI.

We use this attribute to facilitate systems in which multipleABIs coexist, and multiple versions of the same DLL are present. If weare finding an already-loaded code segment, we must find the onewith an ABI matching the importing code segment.Code segments without either kernel or global attributes are standarduser code segments. The kernel needs to attach such code segments to aprocess before they can execute. It will either perform the attach operationat process load time (for the EXE code segment and its dependencies) orwhen a running process loads a DLL.

Each process maintains a list of allcode segments directly attached to it (DProcess::iExeCodeSeg pointsto the main code segment for the process, DProcess::iDynamicCodeis an array of all explicitly dynamically loaded code segments, eachwith its corresponding DLibrary object). This list only contains directlyloaded code segments, not those present solely because they are implicitlylinked to by another code segment. Depending on the memory model,non-XIP code segments may either be visible to all user processes orvisible only to those user processes to which they have been attached.The multiple memory model uses the latter scheme; the other memorymodels use the former.

Kernel code segments are attached to the kernelprocess, but they are not mapped and unmapped; the code segmentis visible from privileged modes immediately on creation. Global codesegments do not need to be attached to any process. They are visible toall processes immediately after creation.A code segment also has flags (iMark), as follows:• EMarkListDeps – temporarily used to mark code segments duringtraversal of the code graph to add code segments to a dependency list• EMarkUnListDeps – temporarily used to mark code segments during traversal of the code graph to remove code segments from adependency list• EMarkLdr – indicates that the code segment is in use by a loadoperation• EMarkLoaded – indicates that the code segment and all its dependencies are fully loaded and fixed up• EMarkDataFlagsValid – indicates that the DataInit and DataPresent flags are valid (taking into account dependencies)• EMarkDataFlagsCheck – used to mark that a code segment hasbeen visited when calculating the DataInit and DataPresentflagsKERNEL-SIDE CODE MANAGEMENT415• EMarkData – indicates that this code segment has .data/.bss andis not an extension or variant (so may require initialization at loadtime – extensions and variants are loaded and initialized before theloader comes into existence so don’t need to be initialized as a resultof any loader operation)• EMarkDataInit – indicates that either this code segment or one inthe sub-graph below it is a DLL with writeable static data, excludingextensions and variants• EMarkDataPresent – indicates that either this code segment orone in the sub-graph below it has writeable static data, excludingextensions and variants.

Note that the difference between EMarkDataPresent and EMarkDataInit is that the former includes EXEswith writeable static data whereas the latter does not• EMarkDebug – reserved for debuggers.We need some form of reference count for code segments to copewith the case in which several processes are using a code segment(for example, two instances of the same EXE or two processes loadingthe same DLL); the kernel can only destroy a code segment when allprocesses have relinquished their reference on it. A code segment shouldonly be destroyed if no currently running process depends on it, andsuch dependence may be indirect via implicit linkages from other codesegments.

We could have done this by reference counting the dependencypointers from each code segment. However, because there may be cyclesin the code graph, this scheme makes it difficult to determine when acode segment may actually be removed. The way to do this would beto traverse the graph in the reverse direction – from the exporting codesegment to the importing code segment – to see if any process is currentlyusing any of the code segments. This would mean that we would needto maintain two sets of dependence pointers for each code segment, onepointing in each direction in the dependence graph.In the reference counting scheme we actually use, we do not referencecount the dependency pointers. Instead, the reference count of eachcode segment is equal to the number of processes which currently havethe code segment loaded, plus 1 if the (user-side) loader is currentlyworking with the code segment.

We indicate the latter case by setting theEMarkLdr flag in the iMark field. When the kernel creates a DCodeSegobject, its access count is 1 and the EMarkLdr flag is set. Following asuccessful load, each code segment in the new dependency tree will bein this state (unless it was already loaded, in which case the access countwill be greater than 1). The kernel then adds the entire dependency treeto the address space of the loader’s client process (or the newly createdprocess if an EXE is being loaded), which causes the access count ofeach code segment to be incremented. Finally, during loader cleanup,416THE LOADERthe kernel decrements the access counts of all code segments with theEMarkLdr flag set and resets the flag, which leaves all code segmentswith the correct access count according to the previous rule.

The kernelperforms the second and third steps (traversing dependence trees or theglobal code segment list and modifying the access counts of several codesegments) with the CodeSegLock mutex held. The access counts of allcode segments must be consistent with the previous rule whenever thismutex is free.To conserve RAM, the kernel shares code segments whenever possible.There will generally only be one code segment for each loaded EXE orDLL with the same code being shared between all processes. There aresome exceptions, which all arise from memory model specific restrictionson data addresses:• On the moving memory model, non-fixed processes share the samedata addresses and so they can share all code segments.

Fixed processes must have unique data addresses, since we designed them sothat a context switch to or from a fixed process should require nochange in the virtual to physical memory map. Symbian OS executables and DLLs do not use position independent code or data,so if a DLL needs to have its .data and .bss at a different address indifferent processes, the kernel must load multiple copies of the DLLand relocate each copy for different code and data addresses. Thismeans that any code segments which either have .data or .bss sectionsor which implicitly link to other such code segments must be uniqueto that process• On the direct memory model and the emulator, all processes musthave unique data addresses and so sharing is possible only for codesegments which don’t have .data/.bss sections and which don’t linkimplicitly (directly or indirectly) to any such code segments.If such an exceptional case is encountered with a non-XIP image file, thekernel will create a second code segment (that is, a second RAM-loadedcopy of the code) from the same image file and relocate it for a differentdata address.

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

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

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

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