Embedding with GNU: Newlib

Total Page:16

File Type:pdf, Size:1020Kb

Embedding with GNU: Newlib Embedding with GNU: Newlib Bill Gatliff 12/28/2001 10:36 AM EST Embedding with GNU: Newlib newlib is often the most appropriate choice for a C runtime library in an embedded system. Read on to find out why. In previous articles in this series, I discussed how to use the GNU compiler and linker (February 2000) and the GNU debugger (September 1999), for embedded development. In this installment, I will introduce newlib, a C runtime library that is often an appropriate choice for embedded software built using GNU tools. Technically, the name newlib refers to a collection of source code assembled by Cygnus Solutions (now Red Hat) from several different origins. This point is interesting only for heritage and licensing purposes (the latter we will discuss momentarily), because the code itself is released, managed, and used as a single functional unit, just as you would expect from any collection of C code distributed under a single name and version number. Newlib is one of several options for small, GNU-friendly C runtime environments (see sidebar "Other Embedded C Runtimes"). It is unique, however, in that it is a mature and well-supported product with an active developer and user base. And its architecture addresses the needs of deeply embedded systems quite well. Other Embedded C Runtime Libraries Clibc (cvs.uclinux.org/) This is the C runtime library behind CLinux, a derivative of the Linux kernel that runs on CPUs without MMUs. This library has a long and convoluted history, with its origins in a version of the GNU C library that predates Linux itself. Clibc is a surprisingly small yet effective library-one can produce a 4KB "Hello, world!" application with CLibc, where the latest full GNU libc requires over 200KB to accomplish the same thing (although, honestly, this isn't exactly an apples-to-apples comparison). In addition, CLibc supports POSIX threads, a useful feature that newlib currently lacks. On the downside, CLibc is still very much under development, and it does not support most of targets currently supported by newlib. In fact, as of December 1, 2000, Clibc only supported x86-the m68k and arm targets were broken (external-lists.valinux.com/archives//sglibc/2000- December/000017.html). Clibc is also a library very much dedicated to a CLinux runtime environment, which makes it difficult to apply to other systems. sglibc (http://external-lists.valinux.com/lists/listinfo/sglibc) sglibc is a very recent attempt to reduce the size of the GNU glibc system. In fact, this project is so new, they don't even have a web page established yet. sglibc attacks the code bloat in glibc by using patches to discard major sections of unneeded or expensive functionality in the glibc source tree. There is considerable discussion underway on the mailing lists as to whether this is a reasonable direction or not, whether the results will be of any use to anyone other than projects needing a thrifty glibc (single- floppy Linux distributions, mostly), and whether the project's principal maintainer even wants to support embedded systems at all! Assuming they can work all of their differences out, sglibc could be the next big thing for embedded Linux and BSD systems, because the GNU C library is the largest single component in today's embedded Linux systems-even larger than the kernel itself. Any gains made here will make Linux increasingly attractive in small, resource-constrained devices. Licensing Because newlib is a collection of source code, it is distributed under the terms of several different licenses. All of the licensing is either public domain or BSD-like, which means that even proprietary applications can adopt newlib because its use does not require distribution of the end work's source code. For convenience, all of newlib's licenses are gathered up into the file COPYING.NEWLIB, which is included with the source code. Features Some of the library's features are useful enhancements to a "typical" embedded setting (whatever that is), while others allow newlib to be about as POSIX-like as a compact C runtime setting can be. A POSIX-like API can be a big help when porting applications to embedded hardware. printf vs. iprintf Newlib contains a complete implementation of the standard printf() and family. By the implementation's own admission, "this code is large and complicated" (vfprintf.c:144), but it is essential for systems that need full ANSI C input and output support, including capabilities for representing and parsing floating-point numbers. Many embedded systems do not use floating-point math, however, and great pains are taken in most embedded runtime libraries to cull this code-bloating functionality whenever possible. Newlib actually approaches this problem in two ways: A FLOATING_POINT macro that allows you to selectively disable floating-point support in each of the stdio library functions that can offer it A new iprintf() function that only knows how to display integer objects If an embedded system needs floating-point support in only a few of the standard input and output functions, newlib can be rebuilt to exclude floating point from places where it isn't needed. You can omit floating point for everything except scanf(), for example, by either undefining the FLOATING_POINT macro everywhere except in the scanf source file, or by modifying newlib's build process to do the same thing, in a more automated fashion. I'll have more to say on these options later, when we look at what it takes to port newlib. For situations where only integer output is required, newlib provides the iprintf() function: a version of printf built without FLOATING_POINT enabled. It behaves exactly like printf, except that it does not understand the %f, %F, %g, or %G type specifiers, and therefore has a much smaller code footprint than its full-featured big brother. More on stdio Newlib's standard input and output facilities are surprisingly complete. The complete C file API is also provided, complete with read and write buffering, seeking, and stream flushing capabilities. Variations like sprintf, fprintf, and vfprintf (takes va_list arguments) are also included, which makes a newlib environment look strikingly similar to one you'd expect to see in a more workstation-oriented programming environment. An unfortunate limitation of newlib's stdio library is that it requires at least a minimal malloc() for proper operation. When the printf() machinery detects a floating-point format specifier, it allocates a few bytes of memory to use as a workspace for constructing the text representation of the number. It's actually a poor design decision, because in other places, newlib statically allocates memory to accomplish the same thing. But that's the way it is. On the plus side, newlib includes a good dynamic memory allocator that is straightforward to set up and use. I have also built a malloc based on a fixed-size memory block allocator, to eliminate fragmentation worries in systems where this was a concern. That code appears in the porting section. Unix API Newlib also includes a lot of the familiar Unix API functions like open() and write(). Most of them map directly to the code stubs newlib uses to invoke external system resources, so their simplicity eliminates the need for malloc(). These stubs will be discussed later, in the section on porting. libm Newlib contains a complete IEEE math library called libm. In addition to offering the standard math functions like exp(), sin(), and pow(), this code also provides matherr(), a modifiable math error handler that the library invokes whenever a serious math-related error, such as an underflow or loss of precision, is detected. By customizing this function, you can handle these situations in whatever way is appropriate for your system. As a surprising bonus, libm also includes functions that take float parameters, instead of double. These extensions are named after their full-precision equivalents. For example, sinf() is the single-precision version of the sin() function. The reduced-precision functions have a considerable speed advantage over their IEEE-compliant double-precision conterparts, which can put some floating-point operations within reach of hardware that is too weak for full double-precision computations. Reentrancy Newlib's C and math libraries are reentrant when properly integrated into a multithreaded environment. The implementation is not obvious at first glance, so I'll spend a few paragraphs describing how it works. Once you know the details, it will be clear how to make sure you set it up properly in your system. The ANSI C standard specifies a global integer called errno, that the runtime library sets when an error occurs. Once set, errno's value persists until the application clears it, which simplifies error notification by the library but can create reentrancy problems when multiple execution threads are working in the library at the same time-neither thread knows who generated the error. Newlib addresses this problem by redefining errno as a macro that references a global pointer to a structure of type struct _reent (the pointer is called _impure_ptr). (Actually, the errno macro calls the function __errno(), which in turn references __impure_ptr[errno.c:11]. But you get the idea.) This structure contains the traditional errno value specified by ANSI, but it also contains a lot of other stuff, including signal handler pointers and file handles for standard input, output, and error streams. Newlib's errno macro hides all of this from the user, of course. To check for errors, an application only needs to refer to the value of errno, just like it would in any ANSI environment. To determine why an fopen() failed, for example, you still do this: fp = fopen( "myfile.txt", "rw" ); if (fp == NULL) { switch( errno ) { case EACCESS: /* we don't have permissions */ ..
Recommended publications
  • Linux and Electronics
    Linux and Electronics Urs Lindegger Linux and Electronics Urs Lindegger Copyright © 2019-11-25 Urs Lindegger Table of Contents 1. Introduction .......................................................................................................... 1 Note ................................................................................................................ 1 2. Printed Circuits ...................................................................................................... 2 Printed Circuit Board design ................................................................................ 2 Kicad ....................................................................................................... 2 Eagle ..................................................................................................... 13 Simulation ...................................................................................................... 13 Spice ..................................................................................................... 13 Digital simulation .................................................................................... 18 Wings 3D ....................................................................................................... 18 User interface .......................................................................................... 19 Modeling ................................................................................................ 19 Making holes in Wings 3D .......................................................................
    [Show full text]
  • Introduction to Embedded C
    INTRODUCTION TO EMBEDDED C by Peter J. Vidler Introduction The aim of this course is to teach software development skills, using the C programming language. C is an old language, but one that is still widely used, especially in embedded systems, where it is valued as a high- level language that provides simple access to hardware. Learning C also helps us to learn general software development, as many of the newer languages have borrowed from its concepts and syntax in their design. Course Structure and Materials This document is intended to form the basis of a self-study course that provides a simple introduction to C as it is used in embedded systems. It introduces some of the key features of the C language, before moving on to some more advanced features such as pointers and memory allocation. Throughout this document we will also look at exercises of varying length and difficulty, which you should attempt before continuing. To help with this we will be using the free RapidiTTy® Lite IDE and targeting the TTE®32 microprocessor core, primarily using a cycle-accurate simulator. If you have access to an FPGA development board, such as the Altera® DE2-70, then you will be able to try your code out in hardware. In addition to this document, you may wish to use a textbook, such as “C in a Nutshell”. Note that these books — while useful and well written — will rarely cover C as it is used in embedded systems, and so will differ from this course in some areas. Copyright © 2010, TTE Systems Limited 1 Getting Started with RapidiTTy Lite RapidiTTy Lite is a professional IDE capable of assisting in the development of high- reliability embedded systems.
    [Show full text]
  • Embedded C Programming I (Ecprogrami)
    To our customers, Old Company Name in Catalogs and Other Documents On April 1st, 2010, NEC Electronics Corporation merged with Renesas Technology Corporation, and Renesas Electronics Corporation took over all the business of both companies. Therefore, although the old company name remains in this document, it is a valid Renesas Electronics document. We appreciate your understanding. Renesas Electronics website: http://www.renesas.com April 1st, 2010 Renesas Electronics Corporation Issued by: Renesas Electronics Corporation (http://www.renesas.com) Send any inquiries to http://www.renesas.com/inquiry. Notice 1. All information included in this document is current as of the date this document is issued. Such information, however, is subject to change without any prior notice. Before purchasing or using any Renesas Electronics products listed herein, please confirm the latest product information with a Renesas Electronics sales office. Also, please pay regular and careful attention to additional and different information to be disclosed by Renesas Electronics such as that disclosed through our website. 2. Renesas Electronics does not assume any liability for infringement of patents, copyrights, or other intellectual property rights of third parties by or arising from the use of Renesas Electronics products or technical information described in this document. No license, express, implied or otherwise, is granted hereby under any patents, copyrights or other intellectual property rights of Renesas Electronics or others. 3. You should not alter, modify, copy, or otherwise misappropriate any Renesas Electronics product, whether in whole or in part. 4. Descriptions of circuits, software and other related information in this document are provided only to illustrate the operation of semiconductor products and application examples.
    [Show full text]
  • Porting Musl to the M3 Microkernel TU Dresden
    Porting Musl to the M3 microkernel TU Dresden Sherif Abdalazim, Nils Asmussen May 8, 2018 Contents 1 Abstract 2 2 Introduction 3 2.1 Background.............................. 3 2.2 M3................................... 4 3 Picking a C library 5 3.1 C libraries design factors . 5 3.2 Alternative C libraries . 5 4 Porting Musl 7 4.1 M3andMuslbuildsystems ..................... 7 4.1.1 Scons ............................. 7 4.1.2 GNUAutotools........................ 7 4.1.3 Integrating Autotools with Scons . 8 4.2 Repositoryconfiguration. 8 4.3 Compilation.............................. 8 4.4 Testing ................................ 9 4.4.1 Syscalls ............................ 9 5 Evaluation 10 5.1 PortingBusyboxcoreutils . 10 6 Conclusion 12 1 Chapter 1 Abstract Today’s processing workloads require the usage of heterogeneous multiproces- sors to utilize the benefits of specialized processors and accelerators. This has, in turn, motivated new Operating System (OS) designs to manage these het- erogeneous processors and accelerators systematically. M3 [9] is an OS following the microkernel approach. M3 uses a hardware/- software co-design to exploit the heterogeneous systems in a seamless and effi- cient form. It achieves that by abstracting the heterogeneity of the cores via a Data Transfer Unit (DTU). The DTU abstracts the heterogeneity of the cores and accelerators so that they can communicate systematically. I have been working to enhance the programming environment in M3 by porting a C library to M3. I have evaluated different C library implementations like the GNU C Library (glibc), Musl, and uClibc. I decided to port Musl as it has a relatively small code base with fewer configurations. It is simpler to port, and it started to gain more ground in embedded systems which are also a perfect match for M3 applications.
    [Show full text]
  • Porting and Using Newlib in Embedded Systems William Gatliff Table of Contents Copyright
    Porting and Using Newlib in Embedded Systems William Gatliff Table of Contents Copyright................................................................................................................................3 Newlib.....................................................................................................................................3 Newlib Licenses....................................................................................................................3 Newlib Features ....................................................................................................................3 Building Newlib ...................................................................................................................7 Tweaks ....................................................................................................................................8 Porting Newlib......................................................................................................................9 Onward! ................................................................................................................................19 Resources..............................................................................................................................19 About the Author................................................................................................................19 $Revision: 1.5 $ Although technically not a GNU product, the C runtime library newlib is the best choice for many GNU-based
    [Show full text]
  • Anatomy of Cross-Compilation Toolchains
    Embedded Linux Conference Europe 2016 Anatomy of cross-compilation toolchains Thomas Petazzoni free electrons [email protected] Artwork and Photography by Jason Freeny free electrons - Embedded Linux, kernel, drivers - Development, consulting, training and support. http://free-electrons.com 1/1 Thomas Petazzoni I CTO and Embedded Linux engineer at Free Electrons I Embedded Linux specialists. I Development, consulting and training. I http://free-electrons.com I Contributions I Kernel support for the Marvell Armada ARM SoCs from Marvell I Major contributor to Buildroot, an open-source, simple and fast embedded Linux build system I Living in Toulouse, south west of France Drawing from Frank Tizzoni, at Kernel Recipes 2016 free electrons - Embedded Linux, kernel, drivers - Development, consulting, training and support. http://free-electrons.com 2/1 Disclaimer I I am not a toolchain developer. Not pretending to know everything about toolchains. I Experience gained from building simple toolchains in the context of Buildroot I Purpose of the talk is to give an introduction, not in-depth information. I Focused on simple gcc-based toolchains, and for a number of examples, on ARM specific details. I Will not cover advanced use cases, such as LTO, GRAPHITE optimizations, etc. I Will not cover LLVM free electrons - Embedded Linux, kernel, drivers - Development, consulting, training and support. http://free-electrons.com 3/1 What is a cross-compiling toolchain? I A set of tools that allows to build source code into binary code for
    [Show full text]
  • TASKING VX-Toolset for Tricore User Guide
    TASKING VX-toolset for TriCore User Guide MA160-800 (v3.2) February 25, 2009 TASKING VX-toolset for TriCore User Guide Copyright © 2009 Altium Limited. All rights reserved.You are permitted to print this document provided that (1) the use of such is for personal use only and will not be copied or posted on any network computer or broadcast in any media, and (2) no modifications of the document is made. Unauthorized duplication, in whole or part, of this document by any means, mechanical or electronic, including translation into another language, except for brief excerpts in published reviews, is prohibited without the express written permission of Altium Limited. Unauthorized duplication of this work may also be prohibited by local statute. Violators may be subject to both criminal and civil penalties, including fines and/or imprisonment. Altium, TASKING, and their respective logos are trademarks or registered trademarks of Altium Limited or its subsidiaries. All other registered or unregistered trademarks referenced herein are the property of their respective owners and no trademark rights to the same are claimed. Table of Contents 1. C Language .................................................................................................................. 1 1.1. Data Types ......................................................................................................... 1 1.1.1. Bit Data Type ........................................................................................... 2 1.1.2. Fractional Types .......................................................................................
    [Show full text]
  • PDF, Postscript(Tm) and HTML Form
    T2 System Development Environment Creating custom Linux solutions (Compiled from r369) René Rebe Susanne Klaus T2 System Development Environment: Creating custom Linux solutions: (Compiled from r369) by René Rebe and Susanne Klaus Published (TBA) Copyright © 2002, 2003, 2004, 2005, 2006, 2007 René RebeSusanne Klaus This work is licensed under the Open Publication License, v1.0, including license option B: Distribution of the work or derivative of the work in any standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder. The latest version of the Open Publication License is presently available at ht- tp://www.opencontent.org/openpub/. Table of Contents Preface ....................................................................................................................x Audience ..........................................................................................................x How to Read this Book ...................................................................................... x Conventions Used in This Book ......................................................................... x Typographic Conventions .......................................................................... x Icons ........................................................................................................x Organization of This Book ................................................................................ xi This Book is Free ............................................................................................
    [Show full text]
  • Design and Implementation of Embedded Linux System for Networking Devices
    Design and Implementation of Embedded Linux System for Networking Devices Hyun-Joon Cha Distributed Processing and Network Management Laboratory Division of Electrical and Computer Engineering (Computer Science and Engineering) [email protected] POSTECH Design and Implementation of Embedded Linux System (1/24) DP&NM Lab. for Networking Devices Contents • Introduction • Current Embedded Operating Systems • Requirements • Design of Embedded Linux System • Implementation • Conclusions • Future work POSTECH Design and Implementation of Embedded Linux System (2/24) DP&NM Lab. for Networking Devices Introduction • Networking Devices – Devices which has networking capability – Infrastructure of emerging information society • e.g.) Router, Switch, Gateway, Cache engine, Cellular phone, PDA, etc. – Network-capable devices will substitute current dummy and not- connected devices all around – Need more resources, processing power and OSs to coordinate it – Most networking devices use commercial Real-time OSs POSTECH Design and Implementation of Embedded Linux System (3/24) DP&NM Lab. for Networking Devices Introduction – cont’d • Embedded OSs for Networking Devices – Commercial: VxWorks, pSOS, QNX, Nucleus, LynxOS, VRTX, etc. – Free or Almost Free: Xinu, uC/OS, etc. • Frequently Raised Problems from Industry and Academy – No OS approach or using educational OS is harmful – High purchase price and royalty -> affect development cost and device price – Limited target and development platform – OS specific architecture and interface – Technology
    [Show full text]
  • 4. Nios II Software Build Tools
    4. Nios II Software Build Tools May 2011 NII52015-11.0.0 NII52015-11.0.0 This chapter describes the Nios® II Software Build Tools (SBT), a set of utilities and scripts that creates and builds embedded C/C++ application projects, user library projects, and board support packages (BSPs). The Nios II SBT supports a repeatable, scriptable, and archivable process for creating your software product. You can invoke the Nios II SBT through either of the following user interfaces: ■ The Eclipse™ GUI ■ The Nios II Command Shell The purpose of this chapter is to make you familiar with the internal functionality of the Nios II SBT, independent of the user interface employed. 1 Before reading this chapter, consider getting an introduction to the Nios II SBT by first reading one of the following chapters: ■ Getting Started with the Graphical User Interface chapter of the Nios II Software Developer’s Handbook ■ Getting Started from the Command Line chapter of the Nios II Software Developer’s Handbook This chapter contains the following sections: ■ “Road Map for the SBT” ■ “Makefiles” on page 4–3 ■ “Nios II Embedded Software Projects” on page 4–5 ■ “Common BSP Tasks” on page 4–8 ■ “Details of BSP Creation” on page 4–20 ■ “Tcl Scripts for BSP Settings” on page 4–27 ■ “Revising Your BSP” on page 4–30 ■ “Specifying BSP Defaults” on page 4–35 ■ “Device Drivers and Software Packages” on page 4–39 ■ “Boot Configurations for Altera Embedded Software” on page 4–40 ■ “Altera-Provided Embedded Development Tools” on page 4–42 ■ “Restrictions” on page 4–48 © 2011 Altera Corporation.
    [Show full text]
  • Wind River® Vxworks® 7 Third Party License Notices
    Wind River® VxWorks® 7 Third Party License Notices This document contains third party intellectual property (IP) notices for the BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY Wind River® VxWorks® 7 distribution. Certain licenses and license notices THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, may appear in other parts of the product distribution in accordance with the OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN license requirements. ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Trademarks All company, product and service names used in this software are for ACPICA identification purposes only. Version: 20170303 Component(s): Runtime Wind River and VxWorks are registered trademarks of Wind River Systems. Description: Provides code to implement ACPI specification in VxWorks. UNIX is a registered trademark of The Open Group. IBM and Bluemix are registered trademarks of the IBM Corporation. NOTICES: All other third-party trademarks are the property of their respective owners. 1. Copyright Notice Some or all of this work - Copyright (c) 1999 - 2016, Intel Corp. All rights reserved. Third Party Notices 2. License 2.1. This is your license from Intel Corp. under its intellectual property rights. You may have additional license terms from the party that provided you this software, covering your right to use that party's intellectual property rights. 64-Bit Dynamic Linker Version: 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a copy Component(s): Runtime of the source code appearing in this file ("Covered Code") an irrevocable, Description: The dynamic linker is used to load shared libraries.
    [Show full text]
  • Choosing System C Library
    Choosing System C library Khem Raj Comcast Embedded Linux Conference Europe 2014 Düsseldorf Germany Introduction “God defined C standard library everything else is creation of man” Introduction • Standard library for C language • Provides primitives for OS service • Hosted/freestanding • String manipulations • Types • I/O • Memory • APIs Linux Implementations • GNU C library (glibc) • uClibc • eglibc – Now merged into glibc • Dietlibc • Klibc • Musl • bionic Multiple C library FAQs • Can I have multiple C libraries side by side ? • Can programs compiled with glibc run on uclibc or vice versa ? • Are they functional compatible ? • Do I need to choose one over other if I am doing real time Linux? • I have a baremetal application what libc options do I have ? Posix Compliance • Posix specifies more than ISO C • Varying degree of compliance What matters to you ? • Code Size • Functionality • Interoperability • Licensing • Backward Compatibility • Variety of architecture support • Dynamic Linking • Build system Codesize • Dietlibc/klibc – Used in really small setup e.g. initramfs • Bionic – Small linked into every process • uClibc – Configurable • Size can be really small at the expense of functionality • Eglibc – Has option groups can be ( < 1M ) License • Bionic – BSD/Apache-2.0 • Musl - MIT • Uclibc – LGPL-2.1 • Eglibc/Glibc – LGPL-2.1 Assigned to FSF • Dietlibc – GPLv2 • Klibc – GPLv2 • Newlib – some parts are GPLv3 Compliance • Musl strives for ISO/C and POSIX compliance No-mmu • uClibc supported No-mmu Distributions • Glibc is used in
    [Show full text]