WIND RIVER WHITE PAPER

Implementing Basic Memory Protection in VxWorks: A Best Practices Guide Paul Chen Product Manager, Wind River Contents

Implementing Basic Memory Protection in VxWorks: A Best Practices Guide

1. Introduction ...... 1 2. Embedded Device Development Issues ...... 1 Increasing complexity ...... 1 Compressed development times ...... 1 Expanding device functionality ...... 1 Demanding service-based economy ...... 1 Increasingly connected devices ...... 1 3. VxWorks and Memory Protection ...... 1 4. VxWorks Basic Memory Protection ...... 2 Protecting private data ...... 2 Protecting shared data ...... 3 Detecting buffer overruns / underruns ...... 3 5. VxWorks Memory Protection using VxVMI ...... 3 Protecting program code ...... 4 Protecting the interrupt vector table ...... 4 6. VxWorks Memory Protection using VxVMI: Advanced Best Practices .4 Protecting private data ...... 4 Protecting shared data ...... 5 Detecting buffer overruns / underruns ...... 5 Examining virtual memory contexts ...... 5 7. Getting VxVMI ...... 5 VxVMI availability ...... 5 8. Summary ...... 6 1. Introduction bundled with VxWorks, as well as efficiency of both development and Wind River’s VxWorks® is the most VxVMI™, an unbundled Operating debugging phases of projects, widely deployed real-time operating System (OS) Extension for VxWorks thereby improving the device’s time system (RTOS) in the embedded that provides additional memory to market. device market. With over 46 percent protection features and program- share of the embedded RTOS matic to the MMU. The basic Expanding device functionality market1, VxWorks has enabled thou- memory protection features in Embedded devices are becoming sands of customers worldwide to VxWorks utilize the MMU that is open, multifunction, managed appli- deliver millions of reliable, high- present in many of today's proces- ances. Embedded applications will performance products to market — sors to enhance productivity during become increasingly more dynamic rapidly, efficiently and cost-effective- the development and debugging as vendors allow customization ly. To achieve the guaranteed cycles. Use of memory protection (personalization), extensions, and responsiveness and determinism can also improve the reliability and software updates on such devices. that are crucial characteristics of quality of an by Again, memory protection becomes mission- or life-critical applications, reducing security risks in its applica- critical to device reliability. VxWorks supports application devel- tions, and can improve the device’s opment exclusively in kernel (or time to market by making develop- Demanding service-based economy “supervisor”) mode. Executing in a ment and debugging cycles both As the economy becomes progres- flat, non-protected memory space more efficient and effective. To sively more service-based, it grows enables applications to obtain the enable developers to take advantage more dependent on the timeliness utmost performance, determinism, of these benefits, this paper and availability of those services. and application flexibility. Kernel describes some “best practice” Downtime for the provider means a mode execution, however, precludes examples for implementing memory loss of service revenue and customer the ability to take advantage of some protection in VxWorks when design- loyalty. Downtime for the consumer types of memory protection enforced ing reliable embedded applications. means a denial of service access and by a Memory Management Unit user frustration. These consumers, (MMU). Use of an MMU can protect 2. Embedded Device Development unlike desktop users, are extremely application code, kernel code, and Issues intolerant of failures. Systems critical data. This memory protection Over the past few years, Wind River providing these services require pro- is usually accompanied by a cost in has been tracking key trends in the tection from common memory faults reduced system performance, due to embedded device market. The trends to improve their overall robustness. the implementation of a process relevant to this paper involve issues model-based or a message-passing facing the developers of embedded Increasingly connected devices architecture. devices. These issues have a direct When embedded devices are opened As the sophistication of embedded impact on system design require- up to the outside world, they must applications has increased, however, ments, as described below. preserve system reliability and issues of system reliability and robustness through protective protection have become ever more Increasing software complexity measures against inadequately important. If an embedded system Embedded applications comprising debugged or poorly designed third- can withstand some performance several megabytes of code are party applications. degradation, its applications can becoming commonplace. Larger Due to these and other concerns, benefit from memory protection development teams, from different memory protection has assumed mechanisms to improve reliability. divisions or business units or even paramount importance for develop- Errant or poorly designed applica- from different companies, collabo- ers of embedded devices. Using tions can be prevented from having rate on designs and face an VxVMI, developers can meet this harmful or disastrous effects on the increasing challenge to create robust requirement while obtaining the embedded system. Memory protec- applications. System reliability must small footprint, high performance, tion between applications supports a be ensured inherently by a system's reliability, and determinism that “fault containment” concept, and can software design, including OS- VxWorks is known throughout the limit the extent of the effect of cer- provided memory protection, rather industry for providing. tain types of software faults. Memory than by relying on extensive system- protection also assists development, level integration testing. 3. VxWorks and Memory Protection catching memory trashing bugs dur- VxWorks is a task-based RTOS in ing integration or debug cycles that Compressed development times which applications run in kernel (or are often difficult to detect and To remain competitive, developers of “supervisor”) mode. In this mode of diagnose. embedded devices face increasing operation, all of physical memory While VxWorks does not provide pressure to shorten project develop- can be accessible to developers in full memory protection and applica- ment cycles and to bring devices to real-addressing mode. Applications tion isolation, Wind River does offer market more quickly. Use of memory that execute in kernel mode can both basic MMU support that is protection can greatly enhance the achieve the highest performance and

1 “2002 Embedded Market Study,” CMP Media LLC, November 2002. 1 determinism, and have the utmost in address 0x0, the protection of this 4. VxWorks Basic Memory flexibility. One risk, however, of table by VxVMI also enables detec- Protection executing in kernel mode is that any tion of writes to a null address. The basic level of MMU support bun- area of memory — e.g., the applica- dled with VxWorks primarily provides tion code, data, or even the kernel By utilizing VxWorks memory pro- cache-safe buffers (see Chapter 12, itself — can potentially be overwrit- tection, developers of software for “Virtual Memory Interface,” in the ten by software bugs or misbehaving embedded systems can realize the VxWorks Programmer’s Guide). applications. following benefits: Importantly, too, it provides pro- Many processors today provide an grammatic modification of page on-chip or onboard Memory Manage- • Improved efficiency of development status, which enables developers to ment Unit (MMU) that can be used to and debugging implement a basic level of memory protect memory against unintention- Memory protection enables faster protection. al or undesired access. To enable diagnosis of incorrect memory To enable the bundled, basic MMU developers to take advantage of accesses. support in VxWorks, define the con- memory protection in their VxWorks- • Improved system reliability and figuration macro powered embedded devices, Wind robustness INCLUDE_MMU_BASIC. See figure 1. River provides bundled, basic MMU Memory protection helps prevent support and an unbundled OS Exten- bugs from crashing devices. The ability to modify page status sion called VxVMI. Some examples of • Reduced development risk dynamically enables developers to: how memory protection can assist Memory protection helps reduce • Protect private memory the development of VxWorks appli- the possibility that latent bugs in • Protect shared memory cations include: the shipping code, or new bugs • Detect buffer overruns and under- from add-on applications, will runs • Detection of buffer overruns or adversely affect the functionality or underruns performance of devices. Each of these benefits will be dis- Using either the bundled MMU • Improved time to market cussed below. For a summary of support or the APIs provided by More efficient development using basic MMU routines, see vmBaseLib VxVMI, pages allocated around memory protection leads to faster in the VxWorks OS Libraries API local buffers can be write-protect- development cycles. Reference. ed so that attempts to write beyond • Improved device quality buffers can be detected both dur- Memory protection enables safer Protecting private data ing debugging and in commercially code, and more graceful degrada- There are many instances when deployed products and systems. tion of device behavior in the face tasks need to protect data from • Protection of private data of errors. being modified by other tasks. With- Using either the bundled MMU out memory protection, such data support or the APIs provided by While there are certainly cases in would be stored in a global area VxVMI, private data areas can be which applications need to be devel- where any task could read or over- created for tasks that are pro- oped in kernel mode because of their write the data, causing potentially tected from access by other tasks. requirements for determinism or undesirable side effects that may be • Protection of kernel and applica- high performance, there are many difficult to diagnose and debug. tion code cases where use of basic memory VxVMI can automatically write- protection and VxVMI can greatly protect text segment pages in increase the reliability and quality memory, so that attempts to write of embedded devices that use to kernel or application code can VxWorks. be detected during debugging and in deployed products. • Protection of the interrupt vector table VxVMI can automatically write- To enable basic MMU support: protect the interrupt vector table, ® so that attempts to overwrite this • In TORNADO, the project must be a “bootable application” table (usually through corrupted 1. Go to the VxWorks view in the project’s Workspace window memory references) can be 2. Navigate the component tree: [Project name]>hardware>memory>MMU>MMU Mode>basic MMU support detected during debugging and in 3. Right-click on basic MMU support and select Include basic MMU support deployed products. • Detection of null pointer write • To define the macro manually in the configuration header files, define exceptions INCLUDE_MMU_BASIC in config.h Since the interrupt vector table is typically located at memory Figure 1 2 To implement protected private Any task requiring only read-access • Read- and write-protect the memory: to the shared memory area can “guard” pages access it directly; however, any task • Disable access to the first and • Add a routine using taskSwitch- requiring write-access to the shared last pages of the allocated HookAdd()that is called with every memory area must do so using the memory using the macro task switch, to dynamically change access routine. Any write-access VM_STATE_SET() (which calls the state of “private memory” pages attempted outside the access routine vmBaseStateSet() for bundled • Call the macro VM_STATE_SET() will cause a TLB exception, leading MMU support) and (which calls vmBaseStateSet() to detection during debugging. VM_STATE_VALID_NOT for bundled MMU support) • Set the memory pages to Detecting buffer overruns/ 5. VxWorks Memory Protection using VM_STATE_VALID upon entry into underruns VxVMI the task, to enable this task to Memory protection can be used to The OS Extension VxVMI provides manipulate its “private memory” help detect programming errors basic memory protection features, as • Set the memory pages to related to allocated memory buffers well as a programmatic interface to VM_STATE_VALID_NOT upon or to application-defined arrays. the MMU. The memory protection leaving the task, to protect that Common programming errors features are described below, and memory from access by other include attempting to access before section 6 describes some best prac- tasks the beginning of, or beyond the end tices that make use of the MMU APIs. of, a buffer or data structure and To enable VxVMI and memory pro- Tasks can thus create their own pro- using a data structure that grows tection, make sure that VxVMI has tected private memory. If any other larger unexpectedly. been installed. Then define the con- task attempts to access an address By allocating “guard” pages on figuration macro INCLUDE_MMU_FULL. within the space of that context, a either side of a buffer or data All VxVMI routines are then available translation look-aside buffer (TLB) structure, and disabling access to for use in applications. See figure 2. exception will occur, leading to de- those pages, incorrect overrun or tection during debugging. underrun accesses to buffers or data For a summary of VxVMI routines, structures can be detected. see vmLib in the VxWorks OS Libraries Protecting shared data API Reference. Also see Chapter 12, Often, tasks need to share data in a To implement guard pages: “Virtual Memory Interface,” in the protected manner. For example, in a • Allocate memory for the buffer or VxWorks Programmer’s Guide. producer-consumer model, one task data structure will produce data and store them in a • Increase the size requested by particular data structure while two extra pages’ worth of bytes consumer tasks will read the data • The buffer needs to be page to accomplish certain functionality. aligned Protecting the data from being over- • The actual data structure begins written by unauthorized consumers one page length into the allocat- can increase the reliability of the ed memory and ends one page system. length before the end of the allocated memory To implement protected shared data: • Allocate memory for the shared data • E.g., use valloc() • Create a semaphore to control To enable full MMU support: access to the shared data • E.g., use semBCreate() • In TORNADO, the project must be a “bootable application” • Write-protect the shared data area 4. Go to the VxWorks view in the project’s Workspace window • Use the macro VM_STATE_SET() 5. Navigate the component tree: (which calls vmBaseStateSet() [Project name]>hardware>memory>MMU>MMU Mode>full MMU support 6. Right-click on full MMU support and select Include full MMU support for bundled MMU support) and VM_STATE_WRITABLE_NOT NOTE: The TORNADO® IDE user interface will provide a warning if both basic • Create an access routine that can MMU support and full MMU support have been selected, as these are mutually write to the shared memory exclusive options. • Take the semaphore while tem- porarily write-enabling the • To define the macro manually in the configuration header files, define shared memory using INCLUDE_MMU_FULL in config.h VM_STATE_SET() and VM_STATE_WRITABLE Figure 2 3 Protecting program code level routines. Using these routines, from the default global virtual VxVMI can protect program code developers can make data private to memory map from unintentional overwriting — a a task or to a code segment. And as • Add a routine using taskSwitch- common hazard when applications with the basic level of MMU support HookAdd()that is called with every run in kernel mode and bugs cause bundled with VxWorks, developers task switch pointers to reference incorrect can also use VxVMI routines to make • This routine should swap virtual memory locations. To enable portions of memory non-cacheable or memory contexts, saving any program code (text segment) protec- can write-protect portions of memory. prior private context and instal- tion, simply define the configuration ling any new private context macro INCLUDE_PROTECT_TEXT. Protecting private data No additional code is necessary to As described earlier, private data can Tasks with their own protected benefit from VxVMI text segment be protected using the MMU support private memory will allocate and use protection (see figure 3). When the bundled with VxWorks. An alternative memory from this context. If any rebuilt image is downloaded to the implementation can be achieved other task attempts to access an target, all text segment pages will using VxVMI, as described below. address within the space of that automatically be write-protected in context, a TLB exception will occur, memory. Additionally, the text seg- To implement protected private leading to detection during ments of any object modules that are memory using VxVMI: debugging. subsequently loaded using ld() will • For each task that requires protect- The advantage of protecting private also automatically be marked as ed private memory, create a private data using VxVMI is that it will often read-only. When object modules are virtual memory (VM) context using be faster to switch a VM context loaded, memory to be write-protect- vmContextCreate() rather than to dynamically change ed is allocated in page-size • Disable access to the correspon- the state of a number of private data increments. Any attempt to write to a ding addresses in global virtual pages upon task switching (the memory location that is write-pro- memory using the macro bundled support technique). tected will cause a TLB exception. VM_STATE_SET() (which calls For more details on programming vmStateSet() if VxVMI is protected private memory, see Protecting the interrupt vector table installed and full MMU support is “Example 12-1: Private Virtual Mem- VxVMI can protect the interrupt enabled) and ory Contexts” in Chapter 12, “Virtual vector table from unintentional over- VM_STATE_VALID_NOT to ensure Memory Interface," of the VxWorks writing — another common hazard that these pages are inaccessible Programmer’s Guide. when applications run in kernel mode and null pointer errors occur while writing to memory. To enable inter- rupt vector table protection, simply To protect text segments: define the configuration macro INCLUDE_PROTECT_VEC_TABLE. • In TORNADO, the project must be a “bootable application” No additional code is necessary to 1. Go to the VxWorks view in the project’s Workspace window benefit from VxVMI interrupt vector 2. Navigate the component tree: table protection (see figure 4). [Project name]>hardware>memory>MMU>write-protect program text 3. Right-click on write-protect program text and select Include write-protect program text Interrupt vector table protection sets the table to be nonwritable. Any • To define the macro manually in the configuration header files, define attribute changes to the table INCLUDE_PROTECT_TEXT in config.h required by the kernel are made automatically; however, if the appli- Figure 3 cation needs to modify the interrupt vector table, it can use the routine intConnect(), which write-enables the interrupt vector table for the To protect the interrupt vector table: duration of the call. • In TORNADO, the project must be a “bootable application” 6. VxWorks Memory Protection using 1. Go to the VxWorks view in the project’s Workspace window VxVMI: Advanced Best Practices 2. Navigate the component tree: Protecting text segments and the [Project name]>hardware>memory>MMU>write-protect program text interrupt vector table are the basic, 3. Right-click on write-protect vector table and select Include write-protect vector table automatic benefits of using VxVMI. In • To define the macro manually in the configuration header files, define addition, VxVMI provides an API that INCLUDE_PROTECT_VEC_TABLE in config.h allows developers to manipulate the MMU programmatically using low- Figure 4

4 Protecting shared data As described earlier, shared data can be protected using bundled MMU To enable virtual context display: support. VxVMI also enables develop- • In TORNADO, the project must be a “bootable application” ers to protect shared memory, and 1. Go to the VxWorks view in the project’s Workspace window the implementation thereof is essen- 2. Navigate the component tree: tially the same as when using the [Project name]>development tool components>show routines>MMU show routine basic MMU support. 3. Right-click on write-protect program text and select Include write-protect program text For more details on programming protected shared data using VxVMI, • To define the macro manually in the configuration header files, define see “Example 12-2: Nonwritable INCLUDE_MMU_FULL and INCLUDE_SHOW_ROUTINES in config.h Memory” in Chapter 12, “Virtual Memory Interface” of the VxWorks Programmer’s Guide. Figure 5

Detecting buffer overruns/ underruns VxVMI® Availability Also as described earlier, buffer overruns and underruns can be Architecture Family Processor(s) detected using the bundled MMU support APIs. VxVMI can also be Motorola® 68K 68000, 68030, 68040, 68060 MC68030, MC68040, MC68LC040, MC68060, used to detect these errors, again MC68302, MC68EN302 using the same technique as for the Motorola PowerPC™ Motorola MPC8xx MPC823, MPC823e, bun-dled case detailed earlier. By MPC850, MPC850DSL, MPC850SAR, MPC855T, using the macro VM_STATE_SET(), MPC857T, the system will automatically call the MPC860, MPC860DP, MPC860P, proper state-setting routine, vmBase- MPC860SAR, MPC860T, StateSet()or vmStateSet(), based MPC862DT/DP/P/SR/T on whether the bundled MMU ARM® ARM7™ ARM7TDMI®, support or full MMU support with ARM720, ARM720T™, VxVMI is available. ARM740, ARM740T™ ARM9 ARM920T™, ARM940T™, ARM966E-S™ Examining virtual memory contexts ARM10 ARM10 ® StrongARM® StrongARM and SA-110®, SA-1110®, IXP1200, 80200 A virtual memory context can be and XScale™ XScale examined in the debugger that is Hitachi SH SH3 (Big and SH7729, SH7709A, SH7727 ® included with the TORNADO or Little Endian) / DSP ® WIND POWER IDE toolsets. The SH4 (Big and Little SH7750, SH7751 display appears on the standard out- Endian) / FPU put device and provides data about Intel Architecture ® and ® i486, Pentium, Pentium with MMX™ each memory block: its validity, its Pentium II , ®, Pentium II, Pentium II ™ ability to be written, and its ability to Pentium III Pentium III, Pentium III Xeon be cached. This information can be Pentium 4 invaluable when debugging the em- Figure 6 bedded system software.

To enable VxVMI virtual memory con- 7. Getting VxVMI VxVMI availability text display, simply define the VxVMI is an OS Extension for VxVMI is currently available on the configuration macros VxWorks or the VxWorks® architecture families and processors INCLUDE_MMU_FULL and DEVELOPER TOOL KIT (VDT). The in figure 6. INCLUDE_SHOW_ROUTINES. product description and data sheet See figure 5. for VxVMI are available on the Wind In addition, WIND RIVER® Service River Website: Teams have ported VxVMI to several Once virtual context display is http://www.windriver.com/products/ other Motorola PowerPC processors, enabled, call vmContextShow()from vxvmi/index.html. including MPC603, MPC604, MPC750, the shell as necessary to examine a and MPC8260. WIND RIVER Service virtual memory context. Teams would be able to provide these ports or to discuss porting VxVMI to a currently unsupported processor.

5 8. Summary VxWorks is a kernel mode address- ing real-time operating system, but use of features bundled with the operating system or provided by the OS Extension VxVMI affords developers important basic memory protection features. These features, including write-protection of text segments and of the interrupt vector table, can prevent errant or poorly designed applications from having harmful or disastrous effects on the embedded system. In addition, devel- opers can detect buffer overruns and underruns, protect private data from corruption, and provide secure shared data. Use of basic MMU support and VxVMI can help developers using VxWorks for embedded system soft- ware to improve the efficiency and productivity of the debugging phases of development, reducing both devel- opment risk and time to market, and to improve system reliability and robustness, improving overall device quality.

Wind River Worldwide Headquarters Wind River Systems and the Wind River Systems logo are 500 Wind River Way trademarks of Wind River Systems, Inc. and Wind River, Alameda, CA 94501 USA VxWorks, Tornado and Wind are registered trademarks Toll free 1-800-545-WIND of Wind River Systems, Inc. All other names mentioned Phone 1-510-748-4100 are trademarks, registered trademarks or service Fax 1-510-749-2010 marks of their respective companies or organizations. [email protected] Nasdaq: WIND For further information regarding Wind River trademarks, please see: For additional contact information, www.windriver.com/company/terms/trademark.html please see our Web site at www.windriver.com. ©2003 Wind River Systems, Inc. MCL-WP-VXW-0311

6