176
SunLink ASN.1 Compiler User’s Guide Part No.: 801-7837-10 Revision A, August 1994 A Sun Microsystems, Inc. Business 2550 Garcia Avenue Mountain View, CA 94043 U.S.A.

SunLink ASN.1 Compiler User's Guide - Oracle

  • Upload
    others

  • View
    29

  • Download
    0

Embed Size (px)

Citation preview

Page 1: SunLink ASN.1 Compiler User's Guide - Oracle

SunLink ASN.1 Compiler User’s Guide

Part No.: 801-7837-10Revision A, August 1994

A Sun Microsystems, Inc. Business

2550 Garcia AvenueMountain View, CA 94043U.S.A.

Page 2: SunLink ASN.1 Compiler User's Guide - Oracle

PleaseRecycle

1994 Sun Microsystems, Inc.2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A.

All rights reserved. This product and related documentation are protected by copyright and distributed under licensesrestricting its use, copying, distribution, and decompilation. No part of this product or related documentation may bereproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

Portions of this product may be derived from the UNIX® and Berkeley 4.3 BSD systems, licensed from UNIX SystemLaboratories, Inc. and the University of California, respectively. Third-party font software in this product is protected bycopyright and licensed from Sun’s Font Suppliers.

RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the United States Government is subject to the restrictionsset forth in DFARS 252.227-7013 (c)(1)(ii) and FAR 52.227-19.

The product described in this manual may be protected by one or more U.S. patents, foreign patents, or pending applications.

TRADEMARKSSun, Sun Microsystems, Sun Microsystems Computer Corporation, SunSoft, the Sun logo, the SMCC logo, the SunSoft logo,are trademarks or registered trademarks of Sun Microsystems, Inc. UNIX is a registered trademark in the United States andother countries, exculusively licensed through X/Open. Ltd. All other product names mentioned herein are the trademarks oftheir respective owners.

All SPARC trademarks, including the SCD Compliant Logo, are trademarks or registered trademarks of SPARC International,Inc. SPARCstation, SPARCserver, SPARCengine, SPARCworks, and SPARCompiler are licensed exclusively to SunMicrosystems, Inc. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc.

The OPEN LOOK® and Sun™ Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and licensees.Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical userinterfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface,which license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written licenseagreements.

X Window System is a trademark and product of the Massachusetts Institute of Technology.

THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR APARTICULAR PURPOSE, OR NON-INFRINGEMENT.

THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES AREPERIODICALLY ADDED TO THE INFORMATION HEREIN; THESE CHANGES WILL BE INCORPORATED IN NEWEDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES INTHE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

Page 3: SunLink ASN.1 Compiler User's Guide - Oracle

iii

Contents

1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1

1.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

1.2 Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

1.3 Architecture and Functions . . . . . . . . . . . . . . . . . . . . . . . . . 1-5

1.3.1 ASN.1 Macro Preprocessor . . . . . . . . . . . . . . . . . . . . 1-7

1.3.2 ASN.1 Analyzer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8

1.3.3 Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8

1.3.4 C Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9

1.4 Programming Environment . . . . . . . . . . . . . . . . . . . . . . . . 1-10

1.4.1 Buffer Management Package . . . . . . . . . . . . . . . . . . . 1-10

1.4.2 Description Independent Modules . . . . . . . . . . . . . . 1-11

1.4.2.1 Verification and Debugging Facilities . . . . . . . 1-11

1.5 Automatic Generation of Interface Elements . . . . . . . . . . 1-11

1.5.1 High-level Encoding/Decoding . . . . . . . . . . . . . . . . 1-12

1.5.2 Symmetric Low-level Encoding/Decoding . . . . . . . 1-13

Page 4: SunLink ASN.1 Compiler User's Guide - Oracle

iv SunLink ASN.1 Compiler User’s Guide—August 1994

2. Input Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1

2.1 ASN.1 Input File Formats . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1

2.2 Defining Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

2.3 Defining Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5

2.4 Defining Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6

2.5 Grouping Definitions into Modules . . . . . . . . . . . . . . . . . . 2-8

2.5.1 Module Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9

2.5.2 Naming Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9

2.5.3 Exporting Definitions . . . . . . . . . . . . . . . . . . . . . . . . . 2-10

2.5.4 Importing Definitions. . . . . . . . . . . . . . . . . . . . . . . . . 2-13

2.6 Input Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17

2.6.1 Input Text Character Set. . . . . . . . . . . . . . . . . . . . . . . 2-17

2.6.2 Type and Values References. . . . . . . . . . . . . . . . . . . . 2-18

2.6.3 Cross Module References. . . . . . . . . . . . . . . . . . . . . . 2-19

2.6.3.1 Macro References. . . . . . . . . . . . . . . . . . . . . . . . 2-20

2.7 Lexical Definition of Items . . . . . . . . . . . . . . . . . . . . . . . . . 2-20

2.7.1 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20

2.7.2 Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21

2.7.3 Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22

2.7.4 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22

2.8 Formal Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-25

2.8.1 Relevant Associations. . . . . . . . . . . . . . . . . . . . . . . . . 2-26

2.8.1.1 Implementation Size (Maximum) . . . . . . . . . . 2-26

2.8.1.2 Exit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-27

Page 5: SunLink ASN.1 Compiler User's Guide - Oracle

v

2.8.1.3 Primitive Generation. . . . . . . . . . . . . . . . . . . . . 2-29

2.8.1.4 Permissive Elements . . . . . . . . . . . . . . . . . . . . . 2-30

2.9 Value Typematching Rules . . . . . . . . . . . . . . . . . . . . . . . . . 2-31

2.10 Identifier Scoping Rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-36

2.11 Error Detection and Recovery. . . . . . . . . . . . . . . . . . . . . . . 2-37

3. C Language Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1

3.1 Buffer Management Package . . . . . . . . . . . . . . . . . . . . . . . 3-1

3.1.1 Buffer Type Representation . . . . . . . . . . . . . . . . . . . . 3-3

3.1.2 Buffer Management Primitives . . . . . . . . . . . . . . . . . 3-4

3.2 Using the High Level Access . . . . . . . . . . . . . . . . . . . . . . . 3-25

3.2.1 Generating High Level Routines. . . . . . . . . . . . . . . . 3-25

3.2.2 Generation Procedure. . . . . . . . . . . . . . . . . . . . . . . . . 3-26

3.2.3 Generation Rules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28

3.2.3.1 Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-34

3.2.4 Using the High-level Routines . . . . . . . . . . . . . . . . . 3-35

3.2.4.1 Calling Decoding Routines. . . . . . . . . . . . . . . . 3-39

3.2.5 Compiling and Linking . . . . . . . . . . . . . . . . . . . . . . . 3-43

3.2.5.1 Compiler Generated Files. . . . . . . . . . . . . . . . . 3-43

3.3 Using The Symmetric Low Level Access. . . . . . . . . . . . . . 3-45

3.3.1 Generating Structures. . . . . . . . . . . . . . . . . . . . . . . . . 3-45

3.3.1.1 Generation Rules . . . . . . . . . . . . . . . . . . . . . . . . 3-48

3.3.2 Structure Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . 3-50

3.3.3 Calling the Encoding Routine . . . . . . . . . . . . . . . . . . 3-51

3.3.4 Calling the Decoding Routine . . . . . . . . . . . . . . . . . . 3-56

Page 6: SunLink ASN.1 Compiler User's Guide - Oracle

vi SunLink ASN.1 Compiler User’s Guide—August 1994

3.3.5 Offset Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-62

3.3.6 Compiling and Linking . . . . . . . . . . . . . . . . . . . . . . . 3-62

3.3.7 Compiler Generated Files . . . . . . . . . . . . . . . . . . . . . 3-63

3.3.8 Include Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-64

3.4 Object Identifier Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-65

3.5 Advanced Use of the SunLink ASN.1 Compiler . . . . . . . 3-69

3.5.1 Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-70

3.5.2 Routine Description . . . . . . . . . . . . . . . . . . . . . . . . . . 3-70

3.5.3 Decoded Value. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-72

3.5.4 Application Packages . . . . . . . . . . . . . . . . . . . . . . . . . 3-73

3.5.5 Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-76

3.6 Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-78

3.6.1 Error Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-79

3.6.2 Switching Tracing Facility . . . . . . . . . . . . . . . . . . . . . 3-80

3.6.2.1 Interpreting Trace Display . . . . . . . . . . . . . . . . 3-81

4. Using the SunLink ASN.1 Compiler . . . . . . . . . . . . . . . . . . . . . 4-1

4.1 Compiler Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1

4.2 File Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

4.3 Launching the Main Monitor . . . . . . . . . . . . . . . . . . . . . . . 4-3

4.3.1 Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3

4.3.2 Compile-time Options . . . . . . . . . . . . . . . . . . . . . . . . 4-4

4.4 Using the Macro Preprocessor . . . . . . . . . . . . . . . . . . . . . . 4-6

4.5 Using the ASN.1 Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . 4-7

4.6 Using the Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9

Page 7: SunLink ASN.1 Compiler User's Guide - Oracle

vii

4.7 Using the C Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10

4.8 Using the Archive Manager . . . . . . . . . . . . . . . . . . . . . . . . 4-13

4.9 Sample Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

4.9.0.1 demoH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14

4.9.0.2 demoL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Index-1

Page 8: SunLink ASN.1 Compiler User's Guide - Oracle

viii SunLink ASN.1 Compiler User’s Guide—August 1994

Page 9: SunLink ASN.1 Compiler User's Guide - Oracle

ix

Figures

Figure 1-1 General Compiler Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4

Figure 1-2 Implementation Level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4

Figure 1-3 Compiler Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6

Figure 1-4 High-Level Encoding/Decoding. . . . . . . . . . . . . . . . . . . . . . . . . 1-12

Figure 1-5 Low-Level Encoding/Decoding . . . . . . . . . . . . . . . . . . . . . . . . . 1-13

Figure 2-1 Module Definition Organization in Files . . . . . . . . . . . . . . . . . . 2-19

Figure 3-1 Generation Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-28

Figure 3-2 Management of the Memory During Encoding . . . . . . . . . . . . 3-53

Figure 3-3 Management of the Memory During Decoding . . . . . . . . . . . . 3-58

Figure 3-4 Traces Displayed by the Decoding Tracing Facility. . . . . . . . . 3-83

Page 10: SunLink ASN.1 Compiler User's Guide - Oracle

x SunLink ASN.1 Compiler User’s Guide—August 1994

Page 11: SunLink ASN.1 Compiler User's Guide - Oracle

xi

Tables

Table 2-1 Case Rules Imposed in Standard Notation . . . . . . . . . . . . . . . . 2-22

Table 2-2 Case Rules Imposed in Macro Definition . . . . . . . . . . . . . . . . . 2-22

Table 2-3 Reserved Character Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23

Table 2-4 Reserved Identifiers for Useful Types . . . . . . . . . . . . . . . . . . . . 2-23

Table 2-5 Reserved Identifiers for Character String Types. . . . . . . . . . . . 2-24

Table 2-6 Reserved Node Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24

Table 2-7 Values Typematching Compatibility for Simple Types. . . . . . 2-34

Table 2-8 Semantic of Warning and Error Messages. . . . . . . . . . . . . . . . . 2-37

Table 2-9 Lexical Warning and Error Messages. . . . . . . . . . . . . . . . . . . . . 2-41

Table 3-1 Overall Template of Generated Encoding Routine . . . . . . . . . 3-29

Table 3-2 Overall Template for Generated Decoding Routine . . . . . . . . 3-29

Table 3-3 Parameters Generated in Encoding Routines . . . . . . . . . . . . . . 3-30

Table 3-4 Parameters Generated in Decoding Routine . . . . . . . . . . . . . . . 3-32

Table 3-5 Dependencies Between Sources and Includes . . . . . . . . . . . . . 3-43

Table 3-6 Generated Types for Low Level Access . . . . . . . . . . . . . . . . . . . 3-48

Table 3-7 Dependencies Between Sources and Includes . . . . . . . . . . . . . 3-63

Page 12: SunLink ASN.1 Compiler User's Guide - Oracle

xii SunLink ASN.1 Compiler User’s Guide—August 1994

Table 3-8 Error Diagnostic Codes for Decoding . . . . . . . . . . . . . . . . . . . . 3-79

Table 4-1 Suffixes of Generated Files for C Language . . . . . . . . . . . . . . . 4-3

Page 13: SunLink ASN.1 Compiler User's Guide - Oracle

xiii

Preface

Abstract Syntax Notation One (ASN.1) is a basic component in theimplementation of the OSI application and presentation layers. It is used todescribe information in the form of data types that are independent of theprogramming language used to process it.

The SunLink ASN.1 Compiler converts ASN.1 source descriptions intoencoding and decoding routines presented in the C programming language.These routines can then be used to design and develop OSI applications and toimplement non-OSI communication protocols.

See Getting Started with the SunLink ASN.1 Compiler for instructions on how toinstall the SunLink ASN.1 Compiler on your machine.

Who Should Use This BookThis manual describes the components of the SunLink ASN.1 Compiler andprovides guidelines for its use. It is intended for experienced softwareprogrammers and it assumes that you are familiar with the principles ofAbstract Syntax Notation One (ASN.1) and the upper layers of the OSInetwork model.

Page 14: SunLink ASN.1 Compiler User's Guide - Oracle

xiv SunLink ASN.1 Compiler User’s Guide—August 1994

How This Book Is OrganizedThe SunLink ASN.1 Compiler User’s Guide is organized as follows:

Chapter 1, “Introduction,” provides an overview of the Abstract SyntaxNotation One (ASN.1) and describes the architecture and structure of theSunLink ASN.1 Compiler.

Chapter 2, “Input Text Files,” describes the general format of the text files thatare used as input to the SunLink ASN.1 Compiler.

Chapter 3, “C Language Environment,” describes how to customize and usethe SunLink ASN.1 Compiler programming environment.

Chapter 4, “Using the SunLink ASN.1 Compiler,” describes the UNIXcommands and installation components.

Typographic ConventionsThe following table describes the fonts and symbols used in this book.

Table P-1 Typographic Conventions

Typeface orSymbol Meaning Example

Typewriter The names of commands, files,and directories; computeroutput

Edit your .login file.Use ls -a to list all files.system% You have mail.

boldface User input; what you type system% suPassword::

italic Command-line placeholder:replace with an actual name orvalue

To delete a file, type rm filename.

Book titles, new words or termsemphasis

See Chapter 6 in the User’s Guide.These are called class options.You must be root to do this.

Code samples are placed in boxes and may display the following output:

Page 15: SunLink ASN.1 Compiler User's Guide - Oracle

Preface xv

% UNIX C shell prompt system%

$ UNIX Bourne and Korn shellprompt

system$

# Superuser prompt, all shells system#

Table P-1 Typographic Conventions

Typeface orSymbol Meaning Example

Page 16: SunLink ASN.1 Compiler User's Guide - Oracle

xvi SunLink ASN.1 Compiler User’s Guide—August 1994

Page 17: SunLink ASN.1 Compiler User's Guide - Oracle

1-1

Introduction 1

Abstract Syntax Notation One (ASN.1) is used to design and implement theupper layers of the OSI Model protocols (Presentation Layer, ApplicationLayer).

File Transfer protocols (FTAM), Message Handling System protocols (MHS),Directory Services (X500), the Common Management Information Protocol(CMIP), and Remote Operations (ROSE) all make extensive use of ASN.1. It isanticipated that the needs of most of the protocols from the Application Layerof the OSI model, and even non-OSI protocols will encourage the use of ASN.1.

Since ASN.1 is implementation independent and can offer a solution for thepresentation and handling of complex data, the use of ASN.1 is foreseen inareas other than protocol design and implementation. Software and applicationdevelopers working in the area of protocol implementation find that ASN.1facilitates complex and often repetitive tasks. The formal structure of ASN.1helps the developer create efficient, easy to maintain code.

SunLink ASN.1 provides both a compiler and a programming environment.

Page 18: SunLink ASN.1 Compiler User's Guide - Oracle

1-2 SunLink ASN.1 Compiler User’s Guide—August 1994

1

1.1 OverviewSeveral international standards have been published both by ISO and CCITTabout ASN.1 and the Basic Encoding Rules for ASN.1.

The first published CCITT recommendation was X409, from the MHS X4001984 series of recommendations (red book). This standard defines both thenotation and the basic encoding rules to apply for data transfer.

In parallel, ISO published two standards (IS 8824 and IS 8825), the firstdescribing the notation itself, and the second containing the definition of theBasic Encoding Rules for ASN.1.

These two standards were updated in 1986, including additional features suchas Object Identifier, External, and Object Descriptor.

Both sets of standards were technically aligned as the result of the workconducted jointly by ISO and CCITT.

In 1988, CCITT removed X409 from the set of X400 recommendations, andreplaced it by recommendations X208 and X209 in the blue book. The contentsof these documents are technically aligned with the new versions of ISOdocuments (ISO 8824 and ISO 8825).

For detailed information about ASN.1 notation, reference should be made tothe ISO document ISO 8824 (1990).

The development rules for the Compiler were based upon the representation ofinformation as specified in ISO 8824: “Abstract Syntax Notation One (ASN.1)”.Encoding of the information is based on ISO 8825:”Basic Encoding Rules forASN.1”.

The Compiler provides support in the process of designing and implementingprotocols using concepts from the upper layers (Presentation, Application) ofthe OSI reference model. It deals more specifically with the representation andthe encoding of information exchanged between peer entities. Software designis supported by the compiler features to validate coding and to prepare theimplementation phase.

Implementation of the design makes use of coding rules which are defined bythe protocols. The coding rules ensure that the developed software is systemportable.

Page 19: SunLink ASN.1 Compiler User's Guide - Oracle

Introduction 1-3

1

1.2 PrinciplesASN.1 is used to describe information in the form of structured “data types”,which make no assumption about the programming language that is used toprocess the information. Values for data types described using ASN.1 may bepresented in a machine-independent form in accordance with ISO 8825.

• Values for data types described in the programming language, are encodedto produce the machine-independent representation.

• Values from the machine-independent representation are decoded toproduce data type values accepted by the programming language.

The SunLink ASN.1 Compiler converts ASN.1 source descriptions intoencoding and decoding routines presented in the C programming language. Inaddition it offers support for the high and low level design phases:

High level design phase:

• Use of the ASN.1 notation is validated by a completelexical/syntactical/semantical checking.

• Production of hard copy integrated in the tool. This includes compilationand preprocessing listings.

Low level design phase:

• Design of the data encoding/decoding routines interface is derived from theASN.1 description and related comments.

• Data type representations in the target programming language arecontrolled by comments from the ASN.1 description.

• Additional user programmed processes are also derived by description.

Using the encoding and decoding routines generated by the SunLink ASN.1Compiler reduces development costs and allows rapid prototyping ofapplications. Because several applications can share the same same generalencoding/decoding algorithms, specific code is limited to the minimum andthe overall size of applications is reduced. General encoding and decodingalgorithms are validated independently from generated routines. Input forthese algorithms are automatically generated from the ASN.1 description.

Figure 1-1 on page 1-4 shows the an overview of the compiler architecture andFigure 1-2 on page 1-4 illustrates how the C definitions generated by thecompiler are used to represented application variables in encoded form.

Page 20: SunLink ASN.1 Compiler User's Guide - Oracle

1-4 SunLink ASN.1 Compiler User’s Guide—August 1994

1

Figure 1-1 General Compiler Architecture

Figure 1-2 Implementation Level

ASN.1 description

ASN.1 Compiler

Generated C Definitions

Documentation(listings)

ASN.1 Encoding/Decoding Environment

ASN.1 Encoded Value

Application Variables

Generated C Definitions

Page 21: SunLink ASN.1 Compiler User's Guide - Oracle

Introduction 1-5

1

1.3 Architecture and FunctionsThe SunLink ASN.1 Compiler is implemented as several processes (ormodules) which are highlighted in block schematic form in Figure 1-3 onpage 1-6. The functions performed by these individual processes can bedivided into two parts:

1. The compiler, which affects the analysis of one or several data-typedescriptions, is written in accordance with the ASN.1 notation. It runs a fulllexical, syntactical and semantical check on each description, merges severaldescriptions in order to resolve possible cross references, and generatessource code in the C programming language for the specified dataencoding/decoding which is implemented in later steps.

2. A programming environment which provides the general encoding anddecoding algorithms written in the programming language. It includesMemory Management routines for the support of encoded values andvariable length values and provides customization mechanisms for theadaptation and porting of the application to several environments.

At the implementation level, the compiler provides facilities for integratingencoding/decoding operations in any kind of application. Those definitionswhich are automatically generated in the programming language by theCompiler are matched to the specific encoder/decoder interface. In this wayapplications which are compiler derived resolve the connection between ASN.1encoded values and programming language variables by using a modulewhich is generated automatically.

Individual modules may be called by invoking the Main Monitor (plc409 ), oras separate commands. Refer to Figure 1-3 on page 1-6.

The modules called by the Main Monitor are:

• the ASN.1 Macro Preprocessor (pr409 )

• the ASN.1 Analyzer (an409 )

• the Linker (lk409 )

• the C Generator (gn409c )

In order to allow for separate compilation the compiler invokes several passes.Each pass of the compiler relates to a given tool—Macro Preprocessor,Analyzer or Linker.

Page 22: SunLink ASN.1 Compiler User's Guide - Oracle

1-6 SunLink ASN.1 Compiler User’s Guide—August 1994

1

Figure 1-3 Compiler Structure

Self-contained Intermediate Form

ASN.1 Macro Preprocessor (pr409 )

ASN.1 Analyzer (an409 )

Linker (lk409 )

Preprocesslistings

Compilationlistings

ASN.1 source ASN.1 source ASN.1 source

Macro freesource

Macro freesource

Macro freesource

IntermediateForms

IntermediateForms

IntermediateForms

C definitions

C Generator(gn409c )

Other languages

Page 23: SunLink ASN.1 Compiler User's Guide - Oracle

Introduction 1-7

1

1.3.1 ASN.1 Macro Preprocessor

The Macro Preprocessor performs lexical and syntaxical analysis on the ASN.1source. Lexical analysis checks the accuracy of the characters used; syntacticanalysis checks the accuracy of the grammatical rules. It performs thefollowing analysis:

• lexical and syntactic analysis of ASN.1 macro definitions

• lexical and syntactical analysis of references to macros (non-standard textparts)

• expansion of non-standard text into standard notation to respect themapping given in macro definitions

• checks for ambiguity in the macros

By default, the macro Preprocessor is invoked for each input of ASN.1 text,before it is processed by the analyzer.

It removes all the macro definitions from this text, reproducing them withincomments in the resulting expanded file, if it is specified by user atcompilation time. The macro definitions are analyzed, checked, and if valid,registered. Further occurrences of the macro identifier are taken by thePreprocessor to be references to the previously defined macro. Analysis of textis then switched to the syntax which was defined by the macro.

Original text is reproduced in the output file within comments if the userspecifies this option. Text resulting from macro expansion is inserted after theoriginal text.

The Preprocessor may issue some error or warning messages. These messagesare displayed to the terminal and are also inserted as comments in theresulting output text.

The Preprocessor recognizes two types of errors:

• errors in macro definitions

• errors in macro references

A simple error recovery mechanism is provided. Whenever a severe error isencountered, the input text is skipped and analysis resumes at predefinedpoints—for example, the end of the current macro, or the next separator.

Page 24: SunLink ASN.1 Compiler User's Guide - Oracle

1-8 SunLink ASN.1 Compiler User’s Guide—August 1994

1

1.3.2 ASN.1 Analyzer

The analyzer processes input text that is written according to the standardASN.1 notation. It performs the complete checking of the consistency of thistext. It also performs analysis of the special comments annotating the typedefinitions that are supported by the compiler.

The ASN.1 Analyser:

• performs lexical and syntactical analysis of ASN.1 standard text

• analyses text consistency

• generates compiled listing, including possible warning and error messages

• produces files containing an intermediate representation of the data—theIntermediate Form File (.if file)

Error and warning messages may be issued by the analyzer. They aredisplayed on the terminal and are also inserted within a compilation listingtogether with the source text.

A sophisticated error recovery mechanism is used to detect, missing,missspelled, or misused keywords, and to make logical assumptions to correctthe error. Warning messages are generated to inform the user.

Where no severe error has been found in the text, the end of the analysisresults in the production of an Intermediate Form File (.if file). This filerepresents the ASN.1 definition and may include references to items that werenot provided in ASN.1 modules of the current input text.

Several .if files may be archived together in order to form an IntermediateForm Library (IFL). This is done with the help of the complementary tool(lib409 ).

1.3.3 Linker

The Linker merges several Intermediate Forms (.if files) produced by theAnalyzer (or archived in a library) in order to resolve all the pendingreferences between ASN.1 modules.

• merge of several .if files resulting from several invocations of the analyzer

• (optional) use of intermediate forms previously archived in a library usingthe archive manager (lib409 )

Page 25: SunLink ASN.1 Compiler User's Guide - Oracle

Introduction 1-9

1

• resolution of references to items not belonging to the same units

• production of a new .if file, with all external references resolved

Modules archived within a library are provided for purposes of cross reference.If a module is referenced simultaneously in a single intermediate form andwithin a library, the Linker chooses the module definition from theIntermediate Form, not the Library form.

Library facilities help in defining sets of ASN.1 descriptions which may bereferenced by other ASN.1 descriptions.

With this mechanism, the user is able to build a specific environment for thedesign of his specifications. This is also useful for projects dealing with largeASN.1 descriptions.

At the end of the link phase, the user is warned of the occurrence of anyunresolved references. Where an unresolved reference exists, the intermediateform is not retained but may be resubmitted following another invocation ofthe Linker. The .if file may also be placed within an archive.

1.3.4 C Generator

The C Generator is used to generate C definitions from the ASN.1 input text.These definitions are used to encode and decode of values for thecorresponding data types.

The C Generator takes an Intermediate Form File, in which all references havebeen resolved by the Linker, as input. It produces readable C source files,which are used by the application to access the programming environment,and a reference listing that documents the generated files.

Four categories of files are produced by the C Generator:

Documentation filesThese files contain listings of the generated interface routine headers andreferences within matrices.

Structure declaration and initialization filesEncoding files reflect the structure of the specification and the tags to beencoded used by the general encoder; decoding files reflect the structure of thespecification, the expected tags, and the optional/default components. Thesefiles are used by the general decoder.

Page 26: SunLink ASN.1 Compiler User's Guide - Oracle

1-10 SunLink ASN.1 Compiler User’s Guide—August 1994

1

Interface routine declaration filesThese files contain data types and structures used for the High-Levelencoding/decoding method. They include routines implementing the interfacebetween the general encoder/decoder and the user application. One encodingroutine and one decoding routine is generated for each ASN.1 type marked inthe specification by a special annotation.

Type and constant translationsThese files are used by the Symmetric Low-Level encoding/decoding method.

1.4 Programming EnvironmentAn encoding/decoding environment is provided in source form. It providesfacilities for:

• Encoding/decoding ASN.1 values to and from C variables.

• Managing large blocks of data

• Integrating and adapting encoding/decoding modules in any environment

A set of customizable definitions is offered which must be adapted accordingto the characteristics of the particular application that is under development.

1.4.1 Buffer Management Package

One of the main difficulties encountered when developing applications dealingwith ASN.1 is the management of large pieces of data for the storage ofencoded values. The programming environment makes use of a BufferManagement Interface, which manipulates octet strings. This interface iscomposed of two elements:

• a type buffer representing the implementation of data pieces

• a set of primitives for manipulating data, including allocating/releasingdata, reading/writing octets from/to data, assembling/fragmenting data,and extending/reducing data

An implementation of this interface is provided by the programmingenvironment.

Page 27: SunLink ASN.1 Compiler User's Guide - Oracle

Introduction 1-11

1

1.4.2 Description Independent Modules

The implementation of ASN.1 encoding/decoding operations is effected asgeneral modules, independent from any specific ASN.1 description values.This generalized treatment of the encoder and decoder enables severalmodules of an application to share the same encoding/decoding module. Italso saves some space in the resulting application, and improves themaintenance of the application.

1.4.2.1 Verification and Debugging Facilities

For reasons of efficiency, no verification of the consistency of the values isperformed during the encoding operations. However, strict verification isenforced during the decoding of values. Where an error is detected in theencoding, the general decoder stops (returns), and the application is informedof the failure of the decoding operation.

Special flags are updated with the error localization and precise diagnosticinformation. Some tracing facilities are also included in the general decoder tohelp debugging.

1.5 Automatic Generation of Interface ElementsThe encoder and decoder are driven by matrices whose definitions areautomatically generated by the compiler. Each matrix reflects the structure, thetags and the optional or default components of the specific ASN.1 description.

The compiler also generates definitions for the generation of the interfacebetween the application and the general encoder/decoder.

The implementation of this interface may take two forms:

• automatically generated routines (for high-level encoding/decoding)

• automatically generated structures (for low-level encoding/decoding)

Page 28: SunLink ASN.1 Compiler User's Guide - Oracle

1-12 SunLink ASN.1 Compiler User’s Guide—August 1994

1

1.5.1 High-level Encoding/Decoding

When the high level interface is used, specific routines are generated by thecompiler for each ASN.1 type which is marked by a special annotation. Theseroutines implement the interface between the application and the generalencoder/decoder.

The generated routines input the buffer containing the ASN.1 encoded values(for constructed data value encoding) and the elementary components of theconcerned type (for primitive data value encoding).

The generated routines call the general encoder/decoder and provide:

• the list of parameters

• the buffer containing the encoded values

• and the matrix reflecting the ASN.1 description

Figure 1-4 High-Level Encoding/Decoding

Application Variables(Generated data types)

Generated routines forencoding

Generated routines fordecoding

Generatedencoding matrix

General Encoder General Decoder

ASN.1 Encoded Value

Generateddecoding matrix

Page 29: SunLink ASN.1 Compiler User's Guide - Oracle

Introduction 1-13

1

1.5.2 Symmetric Low-level Encoding/Decoding

The user application may also access the general encoder/decoder directly. Inthis case, the interface provided by the encoding/decoding package is limitedto two functions:

• a general encoder call

• a general decoder call

The user must provide structures whose fields contain the values to beendcoded. Definitions of types for these structures are automatically generatedby the compiler.

Figure 1-5 Low-Level Encoding/Decoding

Application Variables

User Provided Structures

Generatedencoding matrix

General Encoder General Decoder

ASN.1 Encoded Value

Generateddecoding matrix

Page 30: SunLink ASN.1 Compiler User's Guide - Oracle

1-14 SunLink ASN.1 Compiler User’s Guide—August 1994

1

Page 31: SunLink ASN.1 Compiler User's Guide - Oracle

2-1

Input Text Files 2

This chapter describes the format and use of the text files that act as input tothe SunLink ASN.1 Compiler. It describes how to define data types, datavalues, and macros using ASN.1, and how to group these definitions intomodules.

The SunLink ASN.1 Compiler supports the full ASN.1 standard notation, andperforms all the consistency checks that are imposed by the definition of thisnotation. With some simple restrictions, introduced in order to guarantee aminimum of consistency, it also supports the definition and the use of macros.

2.1 ASN.1 Input File FormatsASN.1 notation, which is designed to describe the structures of the ProtocolData Units (PDU) exchanged by Application Layer Protocols, is derived fromsyntax supported by programming languages such as Pascal or C.

The layout of the files is not significant for the compiler. The ASN.1 text maybe organized as either a single line or several lines, without any semanticimplication. The number of blank characters between two elements is notsignificant and the compiler bases its analysis only on the sequencing of thenon-blank elements in the text. Therefore ASN.1 text may be indentedaccording to any convention. Refer to ISO 8824, clauses 5.4 and 8.1.2 through8.1.5.

Page 32: SunLink ASN.1 Compiler User's Guide - Oracle

2-2 SunLink ASN.1 Compiler User’s Guide—August 1994

2

The source text contained in the file submitted as input to the compiler must becomposed of one or several module definitions. These module definitions mustbe placed in the text one after the other, without any special separator.

You must not insert anything but blank characters or ASN.1 comments outsidea module definition. All the ASN.1 definitions must be included in one of theASN.1 module definitions that are placed in the text.

The following example shows the general format of an ASN.1 input text file:

Note – The form: Module Reference Definitions ::=BEGIN....END may notbe shown in every example that follows.

--**************************************************---- This comment may introduce the whole text ---- Several comments may be placed here ----**************************************************--

Module-A DEFINITIONS ::=BEGIN T1::=INTEGER

-- other definitions of -- -- types -- -- values -- -- macros -- -- may be placed here --

END

-- several definitions of modules may be placed in the same text-- only comments or blanks may separate them

Module-B DEFINITIONS ::= BEGIN T2 ::= SET OF BOOLEANEND

-- Comments or blanks may also be placed before the end-- of the file

Page 33: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-3

2

Within a module definition, consecutive assignments (“::= ”) of types, valuesor macros must be separated by a semicolon character. However, you must notinsert a semicolon separator between the last assignment of a module and thekeyword “END”. This enables the compiler to perform correct error recoverywhen a severe mistake prevents the correct analysis of one of the definitions.

This rule must be carefully respected when copying the text of an ASN.1module from a published standard.

The following example shows assignments within a module:

2.2 Defining TypesThe classical datatypes such as BOOLEAN, INTEGER, REAL, etc. are all availablein ASN.1. Moreover, so as to take into account specific items handled in theProtocol Data Units, some additional datatypes have been created. Theseinclude, for example, ANY or EXTERNAL, for representing User Data, orOBJECT IDENTIFIER, for representing universal references to items.

For example:

My-Module DEFINITIONS::=BEGIN

Type-A ::= BOOLEAN ;value-A TypeA ::= TRUE ;Type-B ::= SET { a INTEGER,

b BOOLEAN OPTIONAL,c OCTET STRING

} ;Type-C ::= SEQUENCE OF Type-B ;value-D INTEGER ::= -234

END

Type-A ::= INTEGER ;

Type-B ::= BOOLEAN ;

Type-C ::= OBJECT IDENTIFIER

Page 34: SunLink ASN.1 Compiler User's Guide - Oracle

2-4 SunLink ASN.1 Compiler User’s Guide—August 1994

2

As for the programming languages, it is possible in ASN.1 to combine severaltypes into structured datatypes with the help of basic constructs. Some of theseconstructs are refined in order to specify the ordering of their components.

For instance, the definition of a PASCAL RECORD may correspond to thedefinition of either a SEQUENCE (ordered transmission of the componentsvalues) or a SET (not ordered transmission of the components values) inASN.1.

For example:

The equivalent definition of an ASN.1 SEQUENCE is shown below, (field valueswill be transmitted in order a-b-c):

The equivalent definition of an ASN.1 SET is shown below, (no constraintimposed on the order in which fields values are transmitted):

Here again, ASN.1 introduces features which are specific to the protocol area,such as the possibility of defining a field as being OPTIONAL. When there is noinput for this value it will not be interpreted as a protocol error.

T : recorda : integer;b : Boolean;c : real

end

T ::= SEQUENCE{ a INTEGER, b BOOLEAN, c REAL}

T ::= SET{ a INTEGER, b BOOLEAN, c REAL}

Page 35: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-5

2

2.3 Defining ValuesIn addition to datatypes, it is also possible to define values with the help ofASN.1. These values may correspond to simple types (like constants inPASCAL), or even to complex structured types, in which case they are definedas aggregates.

Samples of simple ASN.1 value assignments are shown below:

Samples of structured ASN.1 value definitions are shown below.

A sample of values used to specify default values (for components of aSEQUENCE) is shown below.

v1 INTEGER ::= 234;v2 BOOLEAN ::= TRUE

v1 SET { a INTEGER, b BOOLEAN } ::= { a 1 , b TRUE };

v2 SEQUENCE {i1 REAL, i2 INTEGER OPTIONAL, i3 OCTET STRING} ::= { i1 3.27, i3 '0A12'H }

T-octet ::=OCTETSTRING;v-octet T-octet ::='041B3D'H;T-struct ::= SET{ x INTEGER , y BOOLEAN };v-struct ::= { x 0 , y FALSE };

T1 ::= SEQUENCE { a INTEGER DEFAULT 32, b SET OF BOOLEAN DEFAULT {TRUE, FALSE, TRUE} c T-octet DEFAULT v-octet, d T-struct DEFAULT v-struct }

Page 36: SunLink ASN.1 Compiler User's Guide - Oracle

2-6 SunLink ASN.1 Compiler User’s Guide—August 1994

2

2.4 Defining MacrosAlthough syntax of the ASN.1 notation is quite precise and conservative, it alsoprovides a way of defining new syntaxes for the definition of types and theircorresponding values by using macros.

Defining a macro creates a user-defined syntax for Type Notation and ValueNotation. These non-standard syntaxes (i.e. non standard notation) mayintroduce new keywords, and new separators. Macros can also be used todefine alternatives and syntax rules in a BNF-like (Backus Name Form) form.

Macros may be parameterized according to arguments which may be othertypes (simple or structured), values, identifiers, numbers, etc. The result of theexpansion of a macro may refer to these arguments. This is useful to avoidrepetitive definitions of types or values.

The following example shows a macro designed as shorthand-notation:

The macro COUPLE that appears in this example is defined as follows:

COUPLE MACRO::=BEGINTYPE NOTATION ::= “(“type(FirstArg)”,”type(SecondArg)”)”;VALUE NOTATION ::= value (VALUE

-- result of macro : -- SET { a1 FirstArg,

a2 SecondArg OPTIONAL}

)END

T1 ::= COUPLE ( INTEGER , REAL );

T2 ::= COUPLE ( BOOLEAN , COUPLE ( INTEGER,SEQUENCE OF OCTET STRING ));

Page 37: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-7

2

In standard ASN.1, this macro would be:

Macros may also be introduced in order to point out an additional level ofsemantics which cannot be reflected by the standard ASN.1 notation.

A sample of a macro designed for semantic purposes is shown below:

Sample of use of the macro CONFIRMED-SERVICE:

T1 ::= SET { a1 INTEGER, a2 REAL OPTIONAL };

T2 ::= SET{ a1 BOOLEAN, a2 SET { a1 INTEGER, a2 SEQUENCE OF OCTET STRING OPTIONAL } OPTIONAL}

CONFIRMED-SERVICE MACRO ::=BEGINTYPE NOTATION ::= “REQUEST” type(A1) “;”

“RESPONSE” type(A2) ;VALUE NOTATION ::= value( VALUE CHOICE {

from-requester A1, from-responder A2 })

END

Open-PDU ::= CONFIRMED-SERVICEREQUEST Connect-PDU ;RESPONSE CHOICE { ok Accept-Cn-PDU,

nok Refuse-Cn-PDU } ;

Connect-PDU::=SET {.....} ;Accept-Cn-PDU::=[0] SET {...} ;Refuse-Cn-PDU::=[1] SET {...}

Page 38: SunLink ASN.1 Compiler User's Guide - Oracle

2-8 SunLink ASN.1 Compiler User’s Guide—August 1994

2

The equivalent definition in standard notation:

2.5 Grouping Definitions into ModulesModules are defined In order to structure the definitions of types, values andmacros in ASN.1. They are used to package together definitions which aresemantically related.

For example,

Open-PDU ::= CHOICE { from-requester Connect-PDU, from-responder CHOICE

{ ok Accept-Cn-PDU, nok Refuse-Cn-PDU } ;

} ;Connect-PDU::=SET {.....} ;Accept-Cn-PDU::=[0] SET {...} ;Refuse-Cn-PDU::=[1] SET {...}

My-Module DEFINITIONS ::=BEGIN

MY-LIST MACRO ::=BEGINTYPE NOTATION ::= type(Arg1) ;VALUE NOTATION ::= value(VALUE SEQUENCE OF Arg1)END ;

Type-1 ::= INTEGER ;Type-2 ::= SET OF type-1 ;value-2a Type-2 ::= { -12, 100, 20 } ;value-2b Type-2 ::= { 0 } ;PDU-Type ::= SEQUENCE { a Type-2 DEFAULT value-2

b INTEGER, c Type-2 DEFAULT value-2b } ;

Type-3 ::= MY-LIST INTEGEREND -- of module --

Page 39: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-9

2

Module partitioning has no impact upon the actual encoding of the values thatare transferred. It is thus possible to define several ASN.1 modules, and withina given module, to make references to objects (types, values and macrosdefinitions) from the other modules. Note that module definitions withinmodule definitions are not allowed.

2.5.1 Module Definitions

The compiler supports the full module notation from both 1984 and 1988ASN.1 syntaxes. Moreover, the compiler allows the definition of severalmodules in the same source file, or within separate source files, link-editedduring a second pass of the compiler.

The compiler allows the combination of both 1984 notation and 1988 notationin the definition of the modules, and in the declaration of cross-modulereferences (import/export).

2.5.2 Naming Modules

A module definition may be named in two ways:

1984 : a single Module_Reference

1988 : a Module_Reference and an Object_Identifier_Value

For example,

A Module_Reference is a simple identifier which starts with a capital letter.For this compiler and for a given context, Module_Reference must not beredefined.

Module-A1 DEFINITIONS ::=BEGIN....END{object-id} DEFINITIONS ::=Module-B1BEGIN....END

Page 40: SunLink ASN.1 Compiler User's Guide - Oracle

2-10 SunLink ASN.1 Compiler User’s Guide—August 1994

2

An Object_Identifier_Value used as a complement for the naming of themodule definition, represents a universally unique identifier for the moduledefinition. When present, it takes precedence over the Module_Reference forthe naming of the module definition.

The compiler does not support source files in which several modules have thesame Module_Reference , unless there are different complementingObject_Identifier_Values associated to them (second form of naming).

Similarly, the compiler does not support the binding of several source files inwhich a same Module_Reference is associated to more than one moduledefinition, unless there are different Object_Identifier_Valuesassociated with them (second form of naming).

In the case where the conflict of names is solved with the help of theObject_Identifier_Values, the conflicting Module_Reference is nolonger available for referencing the concerned modules; this may lead toproblems when using the 1984 notation for importing objects.

The compiler does not support several module definitions which have thesame Object_Identifier_Value , even if the associatedModule_References are different. This rule applies for module definitionsbelonging to a same source file as well as for module definitions belonging toseparate source files.

In the case of conflicting Object_Identifier_Value for module names, thecompiler simply ignores the Object_Identifier_Value , which is no longeravailable for referencing the concerned modules. This may lead to problemswhen using the 1988 notation for importing objects.

2.5.3 Exporting Definitions

Exporting the type and value definitions enclosed in a module definition issupported by the compiler, with the restriction that value definitions can onlybe exported for reference in the same source file and not from a separate sourcefile. Exporting macro definitions is not supported by the compiler.

The compiler supports two syntaxes for exporting definitions, regardless of thesyntax which is used for naming the module definition (with or without thecomplementing Object_Identifier_Value ):

Page 41: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-11

2

1984 NotationWhen using the 1984 notation, it is only possible to export all the type orvalues definitions enclosed in a module definition. This is simply done byomitting the “EXPORTS …” clause at the beginning of the list of type, valuesor macros assignments.

Note that the use of the 1984 syntax for exporting does not prevent the use ofthe 1988 syntax for importing objects (presence of an “IMPORTS... ” clauseafter the “BEGIN” of the module definition). The following exporting samplesfrom the 1984 notation:

1988 NotationWhen using the 1988 notation, it is possible to give the exact list of exporteddefinitions. This is done by inserting an “EXPORTS... ” clause in front of thelist of type, value or macro assignments.

Module-1 DEFINITIONS ::=BEGIN

-- This module exports T1 and v1 ---- export of M1 is not supported --T1 ::= INTEGER ;v1 BOOLEAN ::= TRUE ;M1 MACRO ::= BEGIN .... END

END

Module-2 { object-id2 } DEFINITIONS ::=BEGIN

-- While this module is named according to ---- 1988 notation, it uses 1984 notation for ---- exporting T2 and v2 --T2 ::= SEQUENCE OF NULL ;v2 SET OF INTEGER ::= { 1, 2, 34 } ;M2 MACRO ::= BEGIN .... END

END

Page 42: SunLink ASN.1 Compiler User's Guide - Oracle

2-12 SunLink ASN.1 Compiler User’s Guide—August 1994

2

The list of exported definitions may be empty, in which case none of theenclosed type or value definitions will be exported.

Note that the use of the 1988 syntax for exporting does not prevent the use ofthe 1984 notation for importing (absence of any “IMPORTS... ” after the“BEGIN” of the module definition).

The identifiers occurring in the list of exported objects must correspond tosome TypeReferences or ValueReferences assigned to types or valuesdefined in the module. The compiler does not allow the same identifier tooccur more than once in this list.

Module-1 DEFINITIONS ::=

BEGINEXPORTS T1;

-- While this module is named according to ---- 1984 notation, it uses 1988 notation to ---- export T1 . Export of M1 is not supported --T1 ::= INTEGER ;v1 BOOLEAN ::= TRUE ;M1 MACRO ::=

BEGIN....END

ENDModule-2 { object-id2 } DEFINITIONS ::=BEGINEXPORTS T2;

M2 MACRO ::= BEGIN .... END-- This module exports T2 ---- but not T3 nor M2 --

T2 ::= SEQUENCE OF T3 ;v2 SET OF INTEGER ::= { 1, 2, 34 } ;T3 ::= NULL ;

END

Page 43: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-13

2

The 1984 (obsolete) manner of referencing objects defined in another module isdone by simply using the notation External_Type_Reference orExternal_Value_Reference of ASN.1 in the body of a module, in a placewhere a defined_Type or defined_Value is acceptable.

The 1988 manner of referencing objects defined in another module is based onan explicit import/export mechanism.

Once an object (type or value) has been defined in a module and declared asexported by this module, it is available for importing by all other modules.This exporting declaration is done via an EXPORTS clause placed after thekeyword “BEGIN” in the module definition.

2.5.4 Importing Definitions

The compiler supports two ways of importing the values or types definitionsfrom another module. The compiler does not support importing macrodefinitions.

1984 NotationWhen using the 1984 notation for importing, all the definitions exported bymodules other than the current one may be referenced in the definitionsenclosed in the current module.

Module-A DEFINITIONS ::=BEGIN

...Type-A ::= SEQUENCE OF Module-B.Type-B...

END

Module-B DEFINITIONS ::=BEGIN

...Type-B ::= [APPLICATION 3] BOOLEAN...

END

Page 44: SunLink ASN.1 Compiler User's Guide - Oracle

2-14 SunLink ASN.1 Compiler User’s Guide—August 1994

2

The syntax consists of omitting the “IMPORTS... ” clause after the “BEGIN” ofthe module definition, and referencing the imported type or value with thehelp of the External_Type_Reference or External_Value_Referencenotation.

The Module_Reference present in the External_Type_Reference orExternal_Value_Reference must correspond to the Module_Referenceused for naming the module which exports the concerned definition. This isdone regardless of the notation (1984 or 1988) which was used forexporting these definitions.

The compiler imposes a restriction concerning the import of a value definition,which is that the module exporting this value must belong to the same sourcefile than the importing module.

Since this notation is only based on the Module_Reference for referencingthe exporting modules, conflicting Module_Reference s may create problemswhen using this notation. The user must not duplicate Module_Reference snames for modules if he intends to use this notation.

Module-1 DEFINITIONS ::= -- exports T1 and v1 --BEGIN

T1 ::= INTEGER ;v1 BOOLEAN ::= TRUE

END

Module-2 { object-id2 } DEFINITIONS ::= -- exports T2 --BEGINEXPORTS T2 ;

T2 ::= SEQUENCE OF T3 ;v2 SET OF INTEGER ::= { 1, 2, 34 } ;T3 ::= NULL

END

Module-A DEFINITIONS ::= -- imports T1 and v1 from ----Module-1-and T2 from Module-2--

BEGINT1 ::= INTEGER ;T-A ::= SEQUENCE OF [0] IMPLICIT Module-1.T1 ;T-B ::= SET OF Module-2.T2 ;v-C SET OF BOOLEAN ::= { Module-1.v1, FALSE }

END

Page 45: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-15

2

1988 NotationWhen using the 1988 notation for importing definitions, it is possible to givethe exact list of objects imported by the current module.

This is done by inserting an “IMPORTS... ” clause after the “BEGIN” of theimporting module.

Within this clause, the imported definitions must be grouped according to theirorigin (i.e. all the imported definitions from a same module must be groupedin the same “FROM... ” statement), since the compiler does not support a samemodule to occur in more than one “FROM” statement of the “IMPORT” clause.

Each “FROM” statement must be composed of the reference to the exportingmodule (placed after the keyword “FROM”), and the exhaustive list ofidentifiers which were assigned in this remote module to the definitions whichare used by the current module. The compiler does not support a sameidentifier to occur more than once in this list of imported definitions in a single“FROM” statement.

However, this identifier may also occur in the list of another “FROM” statement(corresponding to a different remote module); it is also allowed that this sameidentifier should be assigned to a local definition in the current module.

Module1 DEFINITIONS ::=BEGINEXPORTS T1 , T2 ;

T1 ::= INTEGER;T2 ::= BOOLEAN

END

Module2 DEFINITIONS ::=BEGINIMPORTS T1, T2 FROM Module1;

v1 T2 ::= TRUE; -- type : Boolean --v3 T3 ::= 3; -- type : integer --T1 ::= BOOLEAN;T3 ::= Module1.T1

END

Page 46: SunLink ASN.1 Compiler User's Guide - Oracle

2-16 SunLink ASN.1 Compiler User’s Guide—August 1994

2

After this declaration of imported object, the definitions enclosed in the currentmodule may refer to the imported objects either by a simple Type_Referenceor Value_Reference , if there is no risk of ambiguity with a local definitionor with another imported definition identifier. If there is a risk of ambiguity,the External_Type_Reference or External_Value_Reference notationshall be used, and the Module_Reference in these notations shall correspondto the Module_Reference placed to the right of one “FROM” statement. Notethat on the right-hand side of the “FROM” statements, which is the reference tothe remote exporting module, two forms of referencing are allowed:

• Either the remote module is simply referenced by its associatedModule_Reference , in which case the M:Module_Reference serves toreference the remote module and also serves to distinguish the “FROM”statement from the others,

• or the module is referenced by its associated Object_Identifier_Value ,and the Module_Reference placed before is only here to distinguishunambiguously the “FROM” statement from the other similar statement ofthe “IMPORTS” clause.

In the referencing module, the object is imported via an “IMPORTS” clause,specifying the exact module to be searched for the definition of the object.After this, the name of the object may be directly used for reference (as a plainDefined_Type or Defined_Value reference), unless there is a locally definedobject which has the same name. In this case, anExternal_Type_Reference or External_Value_Reference notation isrequired in order to distinguish between a reference to the local object and areference to the imported object.

Module-B { 1 3 1 2 } DEFINITIONS ::=BEGINEXPORTS Type-B

...Type-B ::= [APPLICATION 3] BOOLEAN ;

ENDModule-A { 1 3 1 1 } DEFINITIONS ::=BEGINIMPORTS Type-B FROM Module-B ;

...Type-A ::= SEQUENCE OF Type-B ;..

END

Page 47: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-17

2

2.6 Input LanguageThe SunLink ASN.1 Compiler supports the full ASN.1 standard notation, andperforms all the consistency checks that are imposed by the definition of thisnotation. With some simple restrictions, introduced in order to guarantee aminimum of consistency, it also supports the definition and the use of macros.

2.6.1 Input Text Character Set

Input text submitted to the compiler must be placed into a file containing only7 bit ASCII characters.

The ASN.1 character set defined in the standard is fully supported by thecompiler for the parts of the text which correspond to ASN.1 definitions. Allthe characters shown below are supported.

Any sequence of ASCII blank characters is accepted in a source text betweentwo lexical items. Their number is meaningless to the compiler. These blankcharacters are the following:

Other sequences of characters must form strings properly scanned by lexicalanalysis so as to form lexical items of the ASN.1 notation.

Within ASN.1 comments, all ASCII characters (even those which are not listedabove) may be included. Due to the lexical definition of the ASN.1 comments,the following character strings may not be included in a comment:

A to Za to z0 to 9: = , { } .( ) [ ] - ' "

SPACE (40 in octal)TAB (11 in octal)LINE-FEED (12 in octal)

-- (repetition of minus sign)LINE-FEED (end of line marker)

Page 48: SunLink ASN.1 Compiler User's Guide - Oracle

2-18 SunLink ASN.1 Compiler User’s Guide—August 1994

2

Please note that the dollar sign ($) character may have a special meaning wheninserted at first position in a comment. For further detail, read Section 2.8,“Formal Comments,” on page 2-25. Within ASN.1 macro definitions, literalstrings defining new keywords or separators may include all ASCII charactersbut blank characters.

2.6.2 Type and Values References

The compiler is able to process ASN.1 texts where types and reference typescan be cross linked. Within a module, a type may be used before its definitionwhile another one is declared before it is referenced.

Although ASN.1 texts may be written in any order, adopting a consistentpolicy makes the code easier to maintain. Generally, ASN.1 definitionspublished in the standards are organized in such a way that ASN.1 types andvalues are referenced before their definition.

Remote-Operations-APDUsDEFINITIONS ::=

ROSEapdus ::= CHOICE{ roiv-apdu [1] IMPLICIT ROIVapdu, rors-apdu [2] IMPLICIT RORSapdu, roer-apdu [3] IMPLICIT ROERapdu, rorj-apdu [4] IMPLICIT RORJapdu } ;

ROIVapdu ::= SEQUENCE{ invokeID InvokeIDType, linked-ID [0] IMPLICIT InvokeIDType OPTIONAL, operation-value OPERATION, argument ANY DEFINED BY operation-value

OPTIONAL } ;

IvokeIDType ::= INTEGER ;

RORSapdu ::= SEQUENCE{-- etc ... --

} ;

-- etc ... --

END -- of ROSE protocol specification --

Page 49: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-19

2

2.6.3 Cross Module References

The compiler provides the support for references to objects across modulesbelonging to a same input text or to several input texts provided separately tothe compiler.

Figure 2-1 Module Definition Organization in Files

Within a single source file, the modules must be organized in such a way thata module that is referenced by another module is placed in front of thereferencing module. This organization must be strictly respected, regardless ofthe choice made concerning the organization of type and value assignmentswithin the modules.

PLC409 COMPILER

Merged Output

Module-A DEFINITIONS::=BEGIN........END

Module-B DEFINITIONS::=........End

Module-C DEFINITIONS::=BEGIN........END

Page 50: SunLink ASN.1 Compiler User's Guide - Oracle

2-20 SunLink ASN.1 Compiler User’s Guide—August 1994

2

When the referenced module does not belong to the same source file as themodule that performs the reference, this restriction obviously does not apply.The source files involved in the complete specification are supplied to thecompiler separately and link-edited in a second pass of the compiler. In thiscase only a partial analysis can be performed by the compiler.

2.6.3.1 Macro References

The compiler supports macro notation. This is done during the preprocessingphase. Preprocessing is performed regardless of the module organization, andis run separately for each of the ASN.1 source files that are submitted as inputto the compiler. This implies some restrictions in the way macro definitionsmay be referenced in the ASN.1 source texts.

In order to use a macro notation, the compiler requires that the correspondingmacro definitions should be placed in the same source text as the reference tothis macro, and before any of the references to this macro.

The compiler does not allow the export or import of macro definitions.However, once a macro has been defined in a module, the correspondingmacro notation may be used in the rest of the text of the module (assignmentsentences are placed after the definition of the macro, regardless of the choicetaken for the organization of the type and value assignments in the module).

A macro which is defined in a module may also be accessed in the modulesthat belong to the same source text and that are placed after the module whichcontains its definition. For this reason a macro must not be redefined indifferent modules of the same file.

2.7 Lexical Definition of ItemsThe following items are recognized within ASN.1 notation: comments,numbers, identifiers, and keywords.

2.7.1 Comments

Comments are used to convey additional information about types and values.The following rules are applied to comment items:

1. Comment items are always scanned so as to cover the maximum possibleinput string.

Page 51: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-21

2

2. Comments including a dollar sign ($) as their first significant character arereserved. See Section 2.8, “Formal Comments,” on page 2-25.

3. Within ASN.1 comments, all ASCII characters (even those which are notlisted in Section 2.6, “Input Language,” on page 2-17) may be included.

4. The following character strings may not be included in a comment.

2.7.2 Numbers

Numbers are used to convey sequences of digits that are interpreted asintegers. The following rules are applied to number items:

1. Unlike the restriction imposed in clause 8.8 of CCITT X208Recommendation, the sequence of digits forming a number may start withan unlimited amount of leading '0' digits.

2. A new lexical item, hexadecimal-number , is supported by the compiler. Itmay be used to denote the value of an INTEGER type.

3. A hexadecimal-number consists of a sequence of one or more digits orcapital letters (“A ” to “F”), immediately followed by upper-case letter “H”.For example:

4. Hexadecimal integers must start with a digit.

-- repetition of minus signLINE-FEED end of line (EOL) character

012H01A3H0AH

A0023H is scanned as an “identifier”0A0023H is scanned as a “hexadecimal-number”

Page 52: SunLink ASN.1 Compiler User's Guide - Oracle

2-22 SunLink ASN.1 Compiler User’s Guide—August 1994

2

2.7.3 Identifiers

Identifiers are used to distinguish information as a type, value, module, macro,or other type of data.

1. All the identifiers supported by the compiler are case sensitive, as definedby the standard notation.

2. The compiler is very sensitive to the case of the identifiers. Failure to respectthese rules may lead to complex error recovery by the compiler, with therisk that the automatic correction proposed is not correct. The case rules forstandard notation are defined in Table 2-1.

The case rules for macro definitions are defined in Table 2-2.

2.7.4 Keywords

All ASN.1 keywords are reserved by the compiler. They must be written in alluppercase letters.

Table 2-1 Case Rules Imposed in Standard Notation

Module Reference Initial upper-case letter

Type Reference Initial upper-case letter

Value Reference Initial lower-case letter

Other Identifiers Initial lower-case letter

Table 2-2 Case Rules Imposed in Macro Definition

Macro Reference All upper-case letters

Production Reference Initial upper-case letter

Local Type Reference Initial upper-case letter

Local Value Reference Initial lower-case letter

Page 53: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-23

2

The character sequences in Table 2-3 are reserved for standard notation.

Useful types and string types defined by ASN.1 standard are predefined by thecompiler. Their names are reserved sequences, and it is not possible to define anew type with the same name. However, as the compiler is case sensitive, it ispossible to define new types with the same character sequence, but differentcase.

Reserved predefined types are listed together with their corresponding usefultypes inTable 2-4 and with their corresponding character string types inTable 2-5 on page 2-24.

Table 2-3 Reserved Character Sequences

ABSENT DEFINITIONS INTEGER REAL

ANY END MAX SEQUENCE

APPLICATION ENUMERATED MIN SET

BEGIN EXPLICIT MINUS-INFINITY SIZE

BIT EXPORTS NULL STRING

BY EXTERNAL OBJECT TAGS

BOOLEAN FALSE OCTET TRUE

CHOICE FROM OF UNIVERSAL

COMPONENT INCLUDES OPTIONAL WITH

COMPONENTS IDENTIFIER PRESENT

DEFAULT IMPLICIT PLUS-INFINITY

DEFINED IMPORTS PRIVATE

Table 2-4 Reserved Identifiers for Useful Types

Reserved Identifier Useful Type

EXTERNAL External Type

GeneralizedTime Generalized Time (timestamp)

ObjectDescriptor Object Descriptor (string)

UTCTime Universal Time (timestamp)

Page 54: SunLink ASN.1 Compiler User's Guide - Oracle

2-24 SunLink ASN.1 Compiler User’s Guide—August 1994

2

The standard name of top-nodes used in object identifier declarations arereserved.

Within Formal Comments—that is, special ASN.1 comments starting with adollar sign “$”),—the following keywords are reserved by the compiler.

• entry• exit• implement• permissive• primitive• size

Table 2-5 Reserved Identifiers for Character String Types

Reserved Identifier Character String Type

GraphicString Graphic Character string (G sets)

GeneralString General String type (all G+C sets)

IA5String IA5 string type (ASCII sets)

ISO646String IA5 string type (ASCII sets)

NumericString Numeric String type (digits + space)

PrintableString Printable String type

S100String Videotex String type (see CCITT Rec. S.100)

T61String Teletex String type (see CCITT Rec. T.61)

TeletexString Teletex String type (see CCITT Rec. T.61)

VideotexString Videotex String type (see CCITT Rec. S.100)

VisibleString Visible String type

Table 2-6 Reserved Node Names

ccitt iso

joint-iso-ccitt recommendation

question administration

network-operator standard

identified-organisation member-body

registration-authority

Page 55: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-25

2

2.8 Formal CommentsFormal Comments have been introduced in the notation supported by thecompiler as a deviancy to standard ASN.1 notation. They are used to controlthe form of the objects which are generated by the compiler.

Formal Comments may be used to express directives about:

• the maximum size of the ASN.1 string types

• the maximum number of elements of an ASN.1 sequence or set typereference

• the execution of traps by the decoding routine after the processing of valuesof the annotated type

• the generation of interface primitives for encoding/decoding according tothe high level encoding method. Indication of partial encoding/decodingfor either the high level and symmetric low level encoding method.

• specification of a permissive set or sequence; when decoding the set orsequence, if an unknown element is discovered, this element is dropped.

There is no limitation concerning the number of Formal Comments associatedto a given ASN.1 type. Several formal comments may be attached to the sametype, by preceding this type by a series of Formal Comments, regardless of anylayout and without any special separator.

For example:

However, it is not possible to attach two Formal Comments of the same kind(two “implement size” formal comments, for instance) to a same type. In thiscase, the supplementary occurrences of Formal Comments are ignored, and awarning message is issued by the compiler.

--$ implement size << 10 ----$ exit 330 ----$ implement entry --

SET OF BOOLEAN

--$ implement size << 23 ----$ implement size << 10 -- OCTET STRING-- “implement size <<10" is ignored

Page 56: SunLink ASN.1 Compiler User's Guide - Oracle

2-26 SunLink ASN.1 Compiler User’s Guide—August 1994

2

2.8.1 Relevant Associations

Some categories of Formal Comments are irrelevant when associated withcertain ASN.1 types. Relevant associations are the following ones:

2.8.1.1 Implementation Size (Maximum)

Syntax

The variable nnnnn must be entered in decimal, and be a positive value.

Relevant forEither octet-string type (OCTET STRING) or bit-string type (BITSTRING). In this case, the number nnnnn gives the maximum number of octetsto reserve in the type generated by the compiler for the storage of the decodedvalue.

For example,

Either sequence-of type (“SEQUENCE OF”) or set-of type (“SET OF”). Inthis case, the number nnnnn gives the maximum number of elements to reservein the type generated by the compiler for the storage of the decoded value. Thetwo examples that follow show the use of “implements size” for lists ofelements.

--$ implement size << nnnnn --

--$ implement size << 32 -- OCTET STRING--$ implement size << 132-- BIT STRING--$ implement size << 12 -- NumericString--$ implement size << 2 -- UTCTime

--$ implement size << 40 -- SEQUENCE OF INTEGER--$ implement size << 10 -- SET OF MyType

Page 57: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-27

2

Not relevant forTagged types, type references, or types differing from those listed above.

The following examples are therefore not correct:

The following examples are correct:

2.8.1.2 Exit

Syntax

Relevant forAll ASN.1 types, tagged or not. However, if a type is defined by implicittagging of another type which also has a formal comment “EXIT ”, this newexit takes precedence over the existing one (precedence annotation).

Number nnnnn is provided as a parameter to the user-written exit routine thatwill be called by the General Decoder immediately after the processing ofvalues for the annotated type.

T0 ::= --$ implement size << 10 -- T1 ;

T1 ::= OCTET STRING ;

T0 ::= T1 ;

T1 ::= --$ implement size << 10 -- OCTET STRING ;

--$ exit nnnnn --

Page 58: SunLink ASN.1 Compiler User's Guide - Oracle

2-28 SunLink ASN.1 Compiler User’s Guide—August 1994

2

The following examples illustrate the use of the EXIT formal comment.

The following are examples of precedence annotations:

Not relevant forPlain type references. The following examples are incorrect:

T ::= --$ exit 34 -- SEQUENCE{a INTEGER,b --$ exit 330 -- [PRIVATE 3] SET

{b1 BOOLEAN,b2 OCTET STRING

},c SET OF BIT STRING}

-- exit 34 is activated at the end of the decoding of T-- exit 330 is activated at the end of the decoding of b

T0 ::= --$ exit 43 -- [APPLICATION 3] IMPLICIT T1 ;

T1 ::= --$ exit 44 -- SET{a INTEGER,b BOOLEAN}

-- exit 44 is activated at the end of the decoding of T1

-- exit 43 is activated at the end of the decoding of T0-- in which case exit 44 is not activated

T0 ::= --$ exit 10 -- T1 ;

T1 ::= SET OF BOOLEAN ;

Page 59: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-29

2

Equivalent correct definitions:

2.8.1.3 Primitive Generation

Syntax

Relevant forAll ASN.1 types, tagged or not. This formal comment turns on the generationof high level encoding/decoding primitives for the concerned type.

Be aware that if a type is defined as implicit tagging of another one whichalready has an “implement entry” formal comment, this new type inherits the“implement entry” directive. There is no need to add an extra “implemententry” comment for this tagged type.

For example:

T0 ::= T1 ;

T1 ::= --$ exit 10 -- SET OF BOOLEAN

--$ implement entry --

T1 ::= [APPLICATION 3] IMPLICIT T2 ;T1bis ::= [APPLICATION 4] EXPLICIT T2;T1ter ::= --$ implement entry -- [0] IMPLICIT T2 ;T1last ::= [APPLICATION 2] T2 ;T2 ::= --$ implement entry -- SET

{a OBJECT IDENTIFIER,b BOOLEAN}

-- T1 inherits "implement entry" directive from T2

Page 60: SunLink ASN.1 Compiler User's Guide - Oracle

2-30 SunLink ASN.1 Compiler User’s Guide—August 1994

2

2.8.1.4 Permissive Elements

Syntax

Relevant forEither set type (“SET”) or sequence type (“SEQUENCE”). In this case, whendecoding such a set or sequence, all unknown elements are dropped instead ofreturning a decoding error. This allows you to implement the “rules ofextensibility” mentioned in many protocols.

-- T1bis does not inherit it because tagging is not-- tagged as IMPLICIT but as EXPLICIT

-- directive "implement entry" for T1ter is useless-- because it would inherit it from T2 by implicit-- tagging

-- T1 last inherits "implement entry " directive from-- T2 only in ASN.1 module marked "IMPLICIT TAGS"

--$ permissive --

T1 ::= --$ permissive -- SET{a OBJECT IDENTIFIER,b BOOLEAN}

-- this allows to decode a set where more than these two ---- elements are present ---- example : SET { a OBJECT IDENTIFIER ---- c INTEGER ---- b BOOLEAN ---- } --

Page 61: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-31

2

2.9 Value Typematching RulesThe value typematching rules apply whenever the value notation is used in theASN.1 source. This notation is used when specifying the definition of a valuefor a given type, or when specifying a default value for the component of asequence-type or a set-type .

For example:

In all cases, the value notation must globally match, without ambiguity, thetype for which the value is specified.

During the process of typematching, component values used to build theglobal value may appear to be temporarily ambiguous. In such a case, thecompiler proceeds to analyze the value notation, and tries to solve the pendingambiguities by examining the next component values.

However, after the complete processing of the global value notation, noambiguities must be left.

Module-A DEFINITIONS ::=BEGINv-a SET OF BOOLEAN ::= { TRUE, FALSE, TRUE } ;T1 ::= SEQUENCE

{a INTEGER DEFAULT 3,b [2] IMPLICIT T-b

DEFAULT {x 1, y v-c }} ;

T-b ::= SET{x [0] IMPLICIT INTEGER,y [1] IMPLICIT T-c} ;

v-c T-c ::= '010A'H ;T-c ::= [APPLICATION 2] OCTET STRINGEND

Page 62: SunLink ASN.1 Compiler User's Guide - Oracle

2-32 SunLink ASN.1 Compiler User’s Guide—August 1994

2

With such a mechanism, it is not mandatory to place the name of the typecomponent (set or sequence field, or choice alternative) in front of eachcomponent value enclosed in the global value.

The compiler supports the reference to a previously defined value (locallydefined or imported from another module (for the 1984 notation) placed in thesame source text). However, such a reference cannot be placed in such a waythat its typematching could be ambiguous, even when the rest of the contextmay solve the ambiguity.

v1 T ::= { 1, TRUE, NULL } ;-- equivalent to ---- a1 { e1 1, e2 TRUE, e3 NULL } --

v2 T ::= { 1, TRUE, "abc" } ;-- equivalent to ---- a2 { f1 1, f2 TRUE, f3 "abc" } --

v3 T ::= { 1, TRUE } ;-- ambiguous --

v4 T ::= { TRUE, 1 } ;-- equivalent to ---- a1 { e2 TRUE, e1 1 } --

T ::= CHOICE{a1 SET

{ e1 INTEGER, e2 BOOLEAN, e3 NULL OPTIONAL},

a2 SEQUENCE{ f1 INTEGER, f2 BOOLEAN, f3 OCTET STRING OPTIONAL}

}

Page 63: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-33

2

This point is a restriction to the previous facility. A sample of ambiguous valuereference is given below.

It is possible to limit the ambiguity of matched type for a value by specifyingthe name of the field in front of the value notation.

The example below illustrates how to resolve the previous ambiguity:

The compiler considers that a reference to a defined value is valid if and onlyif the matched type and the type to match are equivalent, according to thefollowing rules:

v1 T1 ::= { fault, NULL } ; -- exact definition of fault -- cannot be determined by the compiler

T1 ::= CHOICE{SEQUENCE {

INTEGER { ok(1), fault(2) }, BOOLEAN },

SET { INTEGER { fault(0), retrieve(1) }, NULL }

}

v1 T1 ::= a1 { fault, NULL } ;-- or

v2 T1 ::= { f1 fault, NULL } ;

T1 ::= CHOICE {

a1 SEQUENCE {e1 INTEGER { ok(1), fault(2) },e2 BOOLEAN },a2 SET {

f1 INTEGER { fault(0), retrieve(1) },f2 NULL }

}

Page 64: SunLink ASN.1 Compiler User's Guide - Oracle

2-34 SunLink ASN.1 Compiler User’s Guide—August 1994

2

Rule 0The following rules must be applied regardless of the tags that may apply onthe top-level of the matched type or the type to match. However, the tags thatmay exist inside the definition of either type must be taken into account.

Rule 1Two types which actually refer to the same use of the type notation, possiblyby relationship to type references, are always equivalent.

Sample of consequence to both rules:

Table 2-7 sums up the compatibility rules for ASN.1 simple types.

1. This compatibility is true regardless of the distinguished values specified for each type.

2. This compatibility is true regardless of the named bits specified for each type.

3. This compatibility is not possible, unless the matched type and the type to match are references to the same use ofthe notation “ENUMERATED...”.

-- the following assignments are allowed --v1 T1 ::= v0 ;v0 [PRIVATE 3] IMPLICIT T0 ::= { TRUE, FALSE } ;T1 ::= [APPLICATION 3] T0 ;T0 ::= SEQUENCE OF BOOLEAN

Table 2-7 Values Typematching Compatibility for Simple Types

Type to match Bool Int OctalString

BitString

Null ObjectId

Enum Real

Bool yes

Int yes1

Octal String yes

Bit. String yes2

Null yes

Object Id yes

Enumeration no3

Real yes

Page 65: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-35

2

Rule 2Two sequence types are never equivalent, even if the description of theircomponents is the same. Therefore, the only case where the matched type andthe type to match are equivalent sequence types is when they both arereferences to the same use of the “SEQUENCE { ... } “ notation.

Rule 3The same rules for sequence types also apply to set types. Two set types arenever equivalent, even if the description of their components is the same.Therefore, the only case where the matched type and the type to match areequivalent set types is when they both are references to the same use of the“SET { ... } ” notation.

v4 SEQUENCE{a INTEGER,b BOOLEAN} ::= v1 ; -- not ok -- -- ( T1 != extensive definition) --

v3 T3 ::= v1 : -- not ok (T1 != T3) --

v2 T2 ::= v1 ; -- ok (T1 = T2) --

v1 T1 ::= { 0, FALSE } ;

T3 ::= SEQUENCE{a INTEGER,b BOOLEAN} ;

T2 ::= T1 ;

T1 ::= SEQUENCE{a INTEGER,b BOOLEAN}

Page 66: SunLink ASN.1 Compiler User's Guide - Oracle

2-36 SunLink ASN.1 Compiler User’s Guide—August 1994

2

Rule 4The same rules for sequence and set types also apply to choice types. Twochoice types are never equivalent, even if the description of their alternatives isthe same. Therefore, the only case where there are equivalent matched typeand type to match which are choice types is when they both are references tothe same use of the “CHOICE... ” notation.

Rule 5Two tagged types are equivalent if and only if:

• tags are either both explicit or both implicit, and

• their respective tag classes are the same, and

• their respective tag identifiers are the same, and

• their respective tagged types are also equivalent.

2.10 Identifier Scoping RulesMost of the identifier scoping rules have already been discussed in previousparts of this chapter. Refer to Section 2.5.2, “Naming Modules,” on page 2-9,Section 2.5.3, “Exporting Definitions,” on page 2-10, Section 2.5.4, “ImportingDefinitions,” on page 2-13, and Section 2.6.3, “Cross Module References,” onpage 2-19.

The following rules also apply:

Identifiers in an Element_Type_List

Identifiers of Named_Types defined in an Element_Type_List are not recognizedoutside of this Element_Type_List. Thus, the following production is allowed:

T1 ::= SET { a [0] SET { a INTEGER , b BOOLEAN } ,b [1] SET { a BOOLEAN , b INTEGER }

}

Page 67: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-37

2

Identifiers in a Selection_Type

if the Choice_Type and the Selection_Type are defined in the same ASN.1 sourcefile, the following production is handled by the compiler:

2.11 Error Detection and RecoveryThe compiler performs complete checking of the consistency of the ASN.1input text. Whenever inconsistencies are detected during the analysis of thetext, the compiler issues a message to the terminal, inserts the same message atthe correct place in the compilation listing, and tries to pursue the analysis ofthe remaining text.

Because the compiler supports several levels of analysis (macro expansion,standard notation syntax checking, and standard notation semantics), themessages may come from different origins. However, the same principles areapplied for all the messages.

Errors are divided into two groups:

• minor errors which the compiler may skip over without taking the risk ofsevere misinterpretation. These errors are signaled by messages qualified as“warning”.

• major errors leading to the termination of the compilation process once thewhole text has been analyzed, thus preventing the generation of any result(besides the compilation listing, of course). These errors are signaled to theuser by messages qualified as “error”.

Selection_Type ::= identifier << Choice_Type

Table 2-8 Semantic of Warning and Error Messages

Error Description

Cannot access type Type is referenced but not defined

Cannot access value Value is referenced but not defined

Type mismatch Value is assigned using a nonappropriate type

Type mismatch: Value expected Value non-defined

Page 68: SunLink ASN.1 Compiler User's Guide - Oracle

2-38 SunLink ASN.1 Compiler User’s Guide—August 1994

2

Alternative name not found Selection type notation is used, butreferenced alternative has not beendeclared in the choice type

Cannot access alternative Selection type notation is used, butreferenced choice type is not found

Alternative ref : Choice typeexpected

In a choice, the selected field does notexist

Ambiguous type for this value Identifier for the chosen type is missing.T1::= CHOICE {a[0] INTEGER, sampleb[1] INTEGER}; v T1::= 3;

Identifier not found Identifier missing

Multiple declaration ofidentifier

An identifier is defined more than once

Tag conflict ; possibly causedby separately defined type

If necessary assign new tag to avoidambiguity

Bad type for COMPONENTS OFconstruct

Type cited is neither SEQUENCE nor SET

Illegally redefining UNIVERSALtag

Bit number must be positive

Already used number; conflict UNIVERSAL for certain tags is reserved

Field name conflict :

Tag conflict with line

Introduces tag conflict on: [%s%s],(line L and line M)

Ignored ; Already used formalcomment

Ignored ; Conflict withprevious constraint about size

Field name identifier must be unique

Ignored ; Such constraint notallowed for this type

Table 2-8 Semantic of Warning and Error Messages (Continued)

Error Description

Page 69: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-39

2

Assumed ; Some constraintsabout tag overwritecorresponding in tagged

Ignored ; Redefinition ofconstraints while referencingtype

Assumed ; Duplicate extensivedefinition of predefined type

FC --$implement size -- invalid for thistype

IMPLICIT tagging of ANY orCHOICE type

Ignored ; not supported kind ofconstraint

ANY or CHOICE may not be implicitlytype` tagged

IMPLICIT tagging of separatelydefined type

Recursive definition of typenot supported

Recursive definition of valuenot supported

Invalid definition level of anexported symbol

Imported type cannot be implicitlytagged

Not in the list of the exportedsymbols or already imported

Import of a type already exported orimported

Invalid value of objectidentifier component

Identifier not found (2) Value of the OBJ ID component is invalid

Bad type for ANY DEFINED BYconstruct

Ambiguous reference to importedsymbol

Ignored; Identifier declarationin conflict with line L

The type for ANY DEFINED BY isinvalid

EXPLICIT tagging assumedinstead of

WARNING that by default EXPLICIT is

Table 2-8 Semantic of Warning and Error Messages (Continued)

Error Description

Page 70: SunLink ASN.1 Compiler User's Guide - Oracle

2-40 SunLink ASN.1 Compiler User’s Guide—August 1994

2

IMPLICIT considered IMPLICIT

Old fashion importing

Invalid base value for REAL

Invalid mantissa value for REAL

Object identifier componentaccepted

(extension) WARNING to import by 1984 rules

Can not import values fromseparate module

SymbolFromModule list isskipped

WARNING, IMPORT of values invalidby 1988 rules

ANY DEFINED BY selector notfound

Skipped part

Subvalues skipped Reference to ANY DEFINED BY notfound

Redefining UNIVERSAL tag WARNING, redefinition of UNIVERSALtag (possible when not reserved)

Previous use of sameAPPLICATION tag

WARNING

Module assumed to be separatelydefined

Module already exists withanother module reference (lineL)

Internal implement size error

Reference to ANY DEFINED BY notfound

WARNING

Invalid constraint

Table 2-8 Semantic of Warning and Error Messages (Continued)

Error Description

Page 71: SunLink ASN.1 Compiler User's Guide - Oracle

Input Text Files 2-41

2

Field not found

Duplicated element or bad order

The two formal comments areincompatible

“implement entry” and “primitive” areincompatible

Table 2-9 Lexical Warning and Error Messages

Error Description

The invalid character c isdeleted.

PLC409 Compiler Analyser tries tocontinue by ignoring a spuriouscharacter in a name/keyword/string

The invalid character c isreplaced by d

PLC409 Compiler Analyser tries tocontinue by replacing a probably validone in a name/keyword/string

The character c is insertedbefore d

PLC409 Compiler Analyser tries tocontinue by inserting a probably validone in a name/keyword/string

s is deleted. PLC409 Compiler Analyser tries tocontinue by ignoring a spurious sequenceof characters

This unknown keyword is erased. PLC409 Compiler Analyser tries to go onby ignoring a keyword

Scanning stops on End Of File PLC409 Compiler Analyser is lost andreaches end of text

Misspelling of s which isreplaced by the keyword k

PLC409 Compiler Analyser detected amisspelling (1 character) in a keyword.Assumes the appropriate one

Misspelling of s before e whichis replaced by the keyword k

PLC409 Compiler Analyser detected amisspelling (1 character) in a keyword.Assumes the appropriate one

s is inserted before d A mandatory keyword/separator/name/string number was missing and hasbeen assumed

Table 2-8 Semantic of Warning and Error Messages (Continued)

Error Description

Page 72: SunLink ASN.1 Compiler User's Guide - Oracle

2-42 SunLink ASN.1 Compiler User’s Guide—August 1994

2

s is replaced by k A keyword/separator was inappropriatehere, the correct one is assumed

k is deleted A keyword/separator was inappropriatehere, it could not be replaced. Thecompiler tries to continue by ignoring it.

s and k are exchanged Two items were inappropriate but wheninverted gave a probable sentence.Compiler tries to continue that way

c before s is replaced by d PLC409 Compiler Analyser detected amisspelling (1 character) in a keyword.Assumes the appropriate one

c before d is deleted

c “ “d is inserted before s

s is inserted before c “ “ d

c “ “ d is replaced by s

c before d is replaced by s “ “t

c is forced before d A mandatory keyword/separator/name/string number was missing and hasbeen assumed

Key_Terminals = { ";”, “END”,“}” , “,” ,

“%FC_END”, “--$”,

“::=”is expected A subsequent series of items wasmissing. It is assumed by the compiler

Major error, skip text Compiler got lost

Parsing resumes on s Compiler stops skipping text, resumesanalysis starting after s

Parsing stops on End Of File Compiler got lost and reached the end offile

Table 2-9 Lexical Warning and Error Messages (Continued)

Error Description

Page 73: SunLink ASN.1 Compiler User's Guide - Oracle

3-1

C Language Environment 3

This chapter provides an overview of the the SunLink ASN.1 Compilerprogramming environment. It describes both the high level access andsymmetric low level access methods used to generate encoding and decodingroutines.

3.1 Buffer Management PackageThe SunLink ASN.1 programming environment represents some of theinformation formats with the help of a type buffer (Asn_buffer ).

The information treated in this way includes:

• unbounded Object Identifier, Octet String and Bit String values

• ASN.1 encoded values, including the values of type Any

Buffers may be required as input to the encoder/decoder, and also as outputby these modules.

Buffers are used to represent and store strings of octets (full 8 bits). Someattributes may be attached to buffers. The following attributes are used by theencoder/decoder:

• length of the buffer (i.e. actual capacity of the buffer in terms of number ofoctets). This attribute is used for all the buffers which are used or providedby the encoder/decoder.

Page 74: SunLink ASN.1 Compiler User's Guide - Oracle

3-2 SunLink ASN.1 Compiler User’s Guide—August 1994

3

• padding bits in the buffer (i.e. number of unused bits in the last octet storedin the buffer). This attribute is only used by the encoder/decoder forunbounded bit-string values used by the encoder or provided by thedecoder.

• read/write index in the buffer (i.e. logical offset in the buffer where the nextread or write operation will take effect).

Operations are performed upon the buffers via a set of primitives which do notdepend on the actual memory management package linked to theprogramming environment.

The programming environment does not depend on a particular buffermanagement package and makes no assumption about the actualimplementation and structure of a buffer type. Instead, it is assumed that a fewprimitives are defined that perform operations upon buffers. These primitivesrepresent the conventional interface that the buffer management packageprovides for the programming environment. They may be linked with aprivate buffer management package, provided that it also provides therequired buffer management primitives.

The same applies for the buffer type itself. The buffer type is denoted as the Cpointer type “Asn_buffer ”, but no other assumption is made by theprogramming environment concerning the structure pointed to by this pointer.However, by convention the representation of an empty buffer is the nullbuffer pointer.

The following operations are expected:

• allocation of a buffer of a given length (ASN_BUF_NEW)

• release of a buffer, even empty (ASN_BUF_RELEASE)

• reset of the read-write index of the buffer to the beginning of this buffer(ASN_BUF_RESET)

• set of the read-write index of the buffer to a given offset in the buffer(ASN_BUF_SET_INDEX)

• read of a given number of octets from a given buffer, starting at the currentposition denoted by the read-write index (ASN_BUF_READ)

• write of a given number of octets into a given buffer, starting at the currentposition denoted by the read-write index (ASN_BUF_WRITE)

• retrieve of the length attribute from a given buffer (ASN_BUF_LENGTH)

Page 75: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-3

3

• assembling of two given buffers into a new buffer (ASN_BUF_APPEND)

• fragmenting of a given buffer at a given position in order to form two newbuffers (ASN_BUF_SPLIT)

• extending a given buffer (even empty) from its beginning for a givennumber of octets (ASN_BUF_ADD_SPACE)

• truncating a given buffer by removing a given number of heading octetsfrom it (ASN_BUF_REM_HEAD)

3.1.1 Buffer Type Representation

The following conventions must be fulfilled by the buffer managementpackage concerning the representation of a buffer.

NameAsn_buffer

ClassDefined in the asn1_runtime.h include file as a C type.

RoleC type used to represent buffers. Used to store BIT STRING, OCTET STRING,ANY, or OBJECT IDENTIFIER values.

Used byGenerated definitionsEncoderDecoder

Properties• An empty buffer is represented by a null pointer, i.e. by the value:

((Asn_buffer ) 0).

• All buffer management primitives use this structure.

Page 76: SunLink ASN.1 Compiler User's Guide - Oracle

3-4 SunLink ASN.1 Compiler User’s Guide—August 1994

3

• Length of a buffer is understood as a number of octets, possibly includingthe last padded octet, if the buffer is used to store a bit string which is notaligned on octet boundaries.

• Read/write index notion is supported. This controls the logical position ofthe buffer (in terms of octets) where the next read/write operation will takeplace. This read/write index is automatically incremented by read/writeoperation. It is possible to reset this index or to set it to a given offset.

• The encoder/decoder ensures that read and write operations are nevermixed. After one or several successive reads, the index is always reset by theencoder/decoder before starting a series of one or several write operations,and vice versa.

3.1.2 Buffer Management Primitives

This section lists the primitives used by the encoder/decoder.

Note that all of these primitives are macros. Also note that whenever someparameters are actually output parameters of the primitive, the parameter typeis not a pointer to the parameter, as would be the case if the primitives weredefined as C functions.

For example, the parameters of the “ASN_BUF_LENGTH(buf, leng) ” primitiveare of the types: “Asn_buffer buf ” and “int leng “ (and not “int *leng ”).

The rest of this section describes the primitives.

Page 77: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-5

3

NameASN_BUF_ADD_SPACE

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byEncoderUser application

RoleExtend the head of the buffer by offset octets.

ConstraintsCaller must ensure that each time this primitive is used:

• actual parameter for buf is a non-register variable. The macro implementingthe primitive may refer to the address of this parameter.

• actual parameter for offset is always positive or null.

Primitive ensures that:

• if buf is actually an empty buffer, then it is allocated with the length offset.

• otherwise the buffer is updated such that there are offset extra octets on itshead, the other original octets being unchanged.

• in all the cases, the length of the updated buffer is always greater than theoriginal length by offset octets.

ASN_BUF_ADD_SPACE(buf,offset)

Asn_buffer buf;int offset;

Page 78: SunLink ASN.1 Compiler User's Guide - Oracle

3-6 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Primitive does not ensure:

• the validity of the read/write index of the updated buffer.

ImplementationSince the encoder makes intensive use of this primitive, proprietaryimplementations should take care that this primitive is optimized.

Page 79: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-7

3

NameASN_BUF_APPEND

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byEncoderUser application

RoleAssembling two buffers to form a new one.

ConstraintsCaller must ensure that:

• actual parameters for oldbuf1, oldbuf2 and newbuf are non-register variables.The macro implementing the primitive may therefore refer to the address ofthese parameters.

Primitive ensures that:

• if oldbuf1 or oldbuf2 is empty (null buffer pointer), then newbuf is equal to theoriginal value of the other buffer.

• otherwise, newbuf is returned as a buffer whose heading octets are thecombined original contents of oldbuf1 and oldbuf2.

• in all cases, oldbuf1 and oldbuf2 are first reset to empty buffers (null bufferpointers), then newbuf is set with the resulting buffer.

• in all cases, the length of the returned buffer is always the sum of theoriginal lengths of the two buffers oldbuf1 and oldbuf2.

ASN_BUF_APPEND(newbuf, oldbuf1, oldbuf2)Asn_buffer newbuf;Asn_buffer oldbuf1;Asn_buffer oldbuf2;

Page 80: SunLink ASN.1 Compiler User's Guide - Oracle

3-8 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Primitive does not ensure:

• the validity of the read/write index of the new buffers.

Page 81: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-9

3

NameASN_BUF_CREATE

ClassDefined as a function in the file asn1_runtime.h .

Format

Used byUser application

RoleCreation of a Asn_buffer using user memory. The memory managementmechanism can create a buffer using user-provided memory that is temporarilyadded to the memory management space. This is useful when, for instance, alarge piece of data has to be decoded. Instead of copying this data into thememory management space with ASN_BUF_NEW followed by ASN_BUF_WRITE,create a buffer pointing to the memory where the data is stored.

ASN_BUF_CREATE(buf,ptr,ulg,rlg,off,id)

Asn_buffer * buf;Char * ptr;int ulg;int rlg;int off;int id;

Page 82: SunLink ASN.1 Compiler User's Guide - Oracle

3-10 SunLink ASN.1 Compiler User’s Guide—August 1994

3

That means that the user data has the following structure:

It is important to note that the offset part and the trailing part although not usedare now owned by the memory management. It is possible that the memorymanagement will use them (as a result of ASN_BUF_ADD_SPACE for example).

The id argument is just additional information which will permit the user toidentify the piece of data he gave to the memory management when this pieceof data has to be given back.

When external data is to be released, the memory management package calls acustomizable function called asn_freedata() in order to give the memoryback to the user.

ptr

rlg

offset ulg

not used significant data not used

trailing

Page 83: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-11

3

NameASN_BUF_LENGTH

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byEncoderUser application

RoleRetrieve the length attribute of the buffer.

ConstraintsCaller must ensure that:

• actual parameter provided for leng is a non-register variable. The macroimplementing the primitive may refer to the address of this parameter.

Primitive ensures that:• if buf is an empty buffer (i.e. null buffer pointer), then the length is

returned as null.• this primitive has no side effect on the attributes or the contents of the

buffer.

ASN_BUF_LENGTH(buf,leng)Asn_buffer buf;int leng;

Page 84: SunLink ASN.1 Compiler User's Guide - Oracle

3-12 SunLink ASN.1 Compiler User’s Guide—August 1994

3

NameASN_BUF_NEW

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byDecoderUser application

RoleGet a buffer of a given length leng. New buffer pointer is assigned to newbuf.

ConstraintsCaller must ensure that each time this primitive is used:

• actual parameter provided for newbuf is a non-register variable. The macroimplementing the primitive may refer to the address of this parameter.

• leng is always a positive or null integer.

Primitive ensures that:• if leng is null integer, then newbuf is set to empty buffer (null buffer

pointer).• read/write index of the new buffer is set to the beginning of the buffer.

ASN_BUF_NEW(newbuf, leng)

Asn_buffer newbuf;int leng;

Page 85: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-13

3

NameASN_BUF_READ

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byEncoderUser application

RoleReads several octets from a buffer, starting at the current location denoted bythe read/write index.

ConstraintsCaller must ensure that:

• actual parameter for buf is a non-register variable. The macro implementingthe primitive may refer to the address of this parameter.

• value parameter for buf is a non-empty buffer (non-null buffer pointer).

• array parameter for string contains at least leng octets, starting from theaddress provided as string.

• value parameter for leng is positive or null.

• the read/write index associated to the buffer denotes a valid logical locationwithin the contents of the buffer.

ASN_BUF_READ(buf,string,leng)

Asn_buffer buf;Char * string;int leng;

Page 86: SunLink ASN.1 Compiler User's Guide - Oracle

3-14 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Primitive ensures that:

• the first octet of the string will be taken from the buffer at the locationdenoted by the original value of the read/write index of the buffer.

• subsequent octets from logically successive locations within the buffer areput in successive octets of the string.

• this operation is repeated for leng octets.

• the read/write index of the updated buffer is logically greater than theoriginal read/write index by leng octets.

• the length of the buffer is left unchanged.

Page 87: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-15

3

NameASN_BUF_RELEASE

ClassSystem (buffer management)

Format

Used byAny environment entity

RoleRelease the buffer and the associated subchain if any.

ConstraintsThe buffer control block is returned to its pool. Fragment descriptors are alsoreturned to their pool. The owner counter of each data segment is decrementedand if it reaches 0 the memory descriptor is returned to its pool and thesegment itself is returned either to the pool (native data segment) or to theuser.

ASN_BUF_RELEASE(bufferp)

Asn_buffer bufferp; /*pointer to buffer address*/

Page 88: SunLink ASN.1 Compiler User's Guide - Oracle

3-16 SunLink ASN.1 Compiler User’s Guide—August 1994

3

NameASN_BUF_REM_HEAD

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byDecoderUser application

RoleRemoves the heading octets of a buffer.

ConstraintsCaller must ensure that:

• the actual parameter provided for buf is a non-register variable. The macroimplementing the primitive may refer to the address of this parameter.

• the value provided for parameter offset does not go past the end of thebuffer, and is always positive or null.

Primitive ensures that:

• if offset is null, then the buffer is left unchanged.

• if offset is equal to the actual length of the buffer, then the buffer is releasedand buf is reset to the empty buffer (null buffer pointer).

• otherwise, the buffer is updated in such a way that the first offset headingoctets of the buffer are removed from it.

ASN_BUF_REM_HEAD(buf,offset)

Asn_buffer buf;int offset;

Page 89: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-17

3

• the length of the updated buffer is always less than the original length byoffset octets.

Primitive does not ensure:

• the validity of the read/write index of the updated buffer.

Page 90: SunLink ASN.1 Compiler User's Guide - Oracle

3-18 SunLink ASN.1 Compiler User’s Guide—August 1994

3

NameASN_BUF_RESET

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byGenerated definitionsEncoderDecoderUser application

RoleReset the read/write index of the buffer.

ConstraintsCaller must ensure that:

• actual parameter for buf is a non-empty buffer (non-null buffer pointer).

Primitive ensures that:

• read/write index of the buffer is reset to the logical position which is thebeginning of the buffer, such that the next read or write operation on thebuffer will take place at the beginning of the buffer.

ASN_BUF_RESET(buf)

Asn_buffer buf;

Page 91: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-19

3

NameASN_BUF_SET_INDEX

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byDecoderUser application

RoleSets the read/write index to a given location in the buffer.

ConstraintsCaller must ensure that each time this primitive is used:

• actual buffer parameter for buf is a non-empty buffer (non-null bufferpointer).

• actual value parameter for offset is less than or equal to the length of thebuffer, and is positive or null.

Primitive ensures that:

• the read/write index of the buffer is updated in such a way that the nextread or write operation performed on this buffer will take place starting atthe logical location denoted by offset. This offset is the number of octetslogically to the left of this location within the contents of the buffer (i.e. nulloffset denotes the beginning of the buffer).

• this primitive has no effect on the other attributes of the buffer, nor on itscontents.

ASN_BUF_SET_INDEX(buf,offset)

Asn_buffer buf;int offset;

Page 92: SunLink ASN.1 Compiler User's Guide - Oracle

3-20 SunLink ASN.1 Compiler User’s Guide—August 1994

3

NameASN_BUF_SPLIT

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byDecoderUser application

RoleSplit old buffer oldbuf in order to form two new buffers, newbuf1 and newbuf2such that:

ConstraintsCaller must ensure that each time this primitive is used:

• actual parameters for newbuf1, newbuf2 and oldbuf are non-register variables.The macro implementing the primitive may therefore refer to the addressesof these parameters.

• The integer leng always denotes a location which does not go past the end ofoldbuf.

Primitive ensures that:

• the buffer newbuf1 contains exactly leng octets taken from the first part ofoldbuf.

• the buffer newbuf2 contains the rest of the octets (second part) of oldbuf.

ASN_BUF_SPLIT(newbuf1, newbuf2, oldbuf, leng)

Asn_buffer newbuf1;Asn_buffer newbuf2;Asn_buffer oldbuf;int leng;

Page 93: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-21

3

• the buffer oldbuf is no longer available after this operation.

• if leng is null, then newbuf1 is returned as an empty buffer (null bufferpointer), and newbuf2 is equal to original value of oldbuf.

• if oldbuf has a length which is exactly equal to leng, then newbuf1 is returnedas the original value of oldbuf, and newbuf2 is returned as an empty buffer(null buffer pointer).

• in all other cases, oldbuf must be first reset to empty buffer (null bufferpointer), then newbuf1 and newbuf2 are respectively set to the 1st part andthe 2nd part of the buffer.

Primitive does not ensure:

• the validity of the read/write index of the new buffers.

Page 94: SunLink ASN.1 Compiler User's Guide - Oracle

3-22 SunLink ASN.1 Compiler User’s Guide—August 1994

3

NameASN_BUF_WRITE

ClassDefined as a macro in the include file asn1_runtime.h .

Format

Used byEncoderUser application

RoleWrites several octets into a buffer, starting at the current location denoted bythe read/write index.

ConstraintsCaller must ensure that:

• actual buffer parameter for buf is a non-register variable. The macroimplementing the primitive may therefore refer to the address of thisparameter.

• value parameter for buf is a non-empty buffer (non-null buffer pointer).

• array parameter for string contains at least leng octets, starting from theaddress provided as string.

• value parameter for leng is positive or null.

• the read/write index associated to the buffer denotes a valid logical locationwithin the contents of the buffer.

ASN_BUF_WRITE(buf,string,leng)

Asn_buffer buf;Char * string;int leng;

Page 95: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-23

3

Primitive ensures that:

• the first octet of the string will be put in the buffer at the location denotedby the original value of the read/write index of the buffer.

• consequent octets from string are put in logically successive locations withinthe buffer.

• this operation is repeated for leng octets from string.

• if there are too many octets in string to be able to put all of them in thecontents of the buffer (leng is too large with respect to the remaining spacein buf), the extra remaining octets from string are ignored.

• the read/write index associated with the updated buffer is logically greaterthan the original read/write index by leng octets.

• the length of the buffer is kept unchanged

Primitive does not ensure:

Page 96: SunLink ASN.1 Compiler User's Guide - Oracle

3-24 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Nameasn_freedata

ClassDefined as a function in the file asn1_runtime.h .

Format

Used byMemory management

RoleRestitution of a piece of memory given by the user with theASN_BUF_CREATE() function. It gives a pointer on the area to restitute (adata)and the identifier given in the id parameter to ASN_BUF_CREATE. The idparameter must be set to a non-zero value before calling ASN_BUF_CREATE..

asn_freedata(adata,id)* adata;int id;

Caution – This function must be customized if the user calls theASN_BUF_CREATE() function.!

Page 97: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-25

3

3.2 Using the High Level AccessHigh level access to the SunLink ASN.1 programming environment isprovided via a set of routines generated by the SunLink ASN.1 Compiler.

3.2.1 Generating High Level Routines

The routines are generated by SunLink ASN.1 Compiler based on the inputASN.1 specification. This generation is controlled by the formal comment “--$implement entry --”. See Section 2.8, “Formal Comments,” on page 2-25.

An implement entry formal comment must be placed immediately before eachASN.1 type, or element of type, for which you want to generate a primitive.Although implement entry formal comments may be associated to any kind ofASN.1 type, or type element, such comments cannot be placed in front of atype-reference; if required, the implement entry formal comment must beplaced in the assignment where the referenced type is defined.

For example, an incorrect use of the implement entry formal comment:

Equivalent correct definitions:

The SunLink ASN.1 Compiler will only generate primitives providedimplement entry formal comments; therefore, these comments must be addedto plain ASN.1 text that appears in published specifications in order to use thehigh level access method.

The primitives are deduced from annotated ASN.1 text according to simplerules. The compiler also generates listings summing up all the headers of theprimitives it generates. Thus, the design of the interface for encoding anddecoding via high-level primitives may be controlled and refined by the user.

T0 ::= --$ implement entry -- T1 ;

T1 ::= SET OF BOOLEAN ;

T0 ::= T1 ;

T1 ::= --$ implement entry -- SET OF BOOLEAN ;

Page 98: SunLink ASN.1 Compiler User's Guide - Oracle

3-26 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.2.2 Generation Procedure

Start by inserting an implement entry formal comment in front of each ASN.1type which corresponds to data units to be encoded. Then, after havingprocessed the ASN.1 text using the SunLink ASN.1 Compiler, look at thelisting of generated routine headers (see Chapter 4, “Using the SunLink ASN.1Compiler).

Refine the generated primitives by adding supplementary implement entryformal fomments in front of the major components of the data units. Thesesupplementary implement entry formal comments may be added in front ofany component of the main ASN.1 types.

For example:

Adding formal comments to substructures reduces the number of parametersincluded in the primitives generated for the main ASN.1 type. The elementarycomponents of the concerned substructures are no longer seen from the mainlevel, but are handled via supplementary generated primitives, correspondingto these substructures.

Pdu ::= --$ implement entry --SET { parm-1 Param1, parm-2 OCTET STRING, parm-3 --$ implement entry --

SET {

p3-1 BIT STRING,p3-2 REAL

} } ;

Param1 ::= --$ implement entry -- SEQUENCE{ p1-1 INTEGER, p1-2 BOOLEAN}

Page 99: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-27

3

In the previous example, instead of having one single primitive for the maintype, with the following description:

Adding the extra implement entry formal comments (shown in bold) givesthree pairs of generated primitives, with the following descriptions:

By successively inserting additional implement entry formal comments, theuser can generate a set of encoding/decoding primitives which is adequate fora given application.

The architecture of the generated primitives should match with the userapplication in terms of its modules, organization, and information flow. Thisdecision is largely subjective. In general, if a set of parameters has to beprocessed by a given module, and these parameters are not used by any othermodule, but are taken as an aggregate of values, then it may be suitable tohave this set of parameters encoded and decoded by a separate pair ofencoding/decoding primitives.

encode/decode Pdu with :- value of p1-1- value of p1-2- value of parm-2- value of p3-1- value of p3-2

encode/decode Pdu with :

-encoding of parm-1-value of parm-2-encoding of parm-3

encode/decode parm-1/Param1 with :

-value of p1-1-value of p1-2

encode/decode parm-3 with :

-value of p3-1-value of p3-2

Page 100: SunLink ASN.1 Compiler User's Guide - Oracle

3-28 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Figure 3-1 Generation Processing

Proceeding by successive retries is the best method to use in order to generatean adequate set of encoding/decoding primitives.

Summary of Steps1. Put an implement entry comment in front of each main ASN.1 type

(i.e. each description of a PDU).

2. Process the ASN.1 text using the SunLink ASN.1 Compiler.

3. Inspect the listing of headers of the generated primitives.

4. Reduce the number of parameters by adding implement entry formalcomments for sub-structures which are logically processed separately in theapplication.

5. Repeat steps 2 to 4 until the primitives are adequately defined.

3.2.3 Generation Rules

The SunLink ASN.1 Compiler deduces the parameters of the generatedprimitives by collecting all the elementary elements composing the typeassociated with the implement entry formal comment.

retriesASN.1 description

Generated Definitions

PLC409 COMPILER Listings

Page 101: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-29

3

All the generated routines have the same general form, independent of theassociated type for which they are generated. The general forms of encodingand decoding routines are shown in Table 3-1 and Table 3-2.

The last parameter is always the result of encoding (expanded on the left ifprovided as non-null buffer, otherwise allocated by the generated routine).

The first parameter is always the result of encoding (truncated on the left if stillsome stuff following the ASN.1 T-L-V in the buffer. Otherwise, it is released bythe generated routine. Value returned by function is null if no error. SeeSection 3.6.1, “Error Detection,” on page 3-79for more details.

Table 3-1 Overall Template of Generated Encoding Routine

Type General Form of Encoding Routine

XXXX ::=--$ implement entry --

type

CXXXX ( ....... parameters generated for type

or .......

buffer)

Asn_buffer * buffer;

Table 3-2 Overall Template for Generated Decoding Routine

Type General Form of Decoding Routine

XXXX ::=--$ implement entry --

type

Asn_u_intx DXXXX ( resbuf, .......

parameters generated fortype

.......)

Asn_buffer * resbuf;

XXXX ::=--$ implement entry --

type

Asn_u_intx DXXXX ( resbuf, .......

Page 102: SunLink ASN.1 Compiler User's Guide - Oracle

3-30 SunLink ASN.1 Compiler User’s Guide—August 1994

3

According to the definition of each component of the marked by the implemententry formal comment, the SunLink ASN.1 Compiler adds new parameters tothe C primitive that is generated. The correspondence between the nature ofthe component and the C type of the parameter is given in Table 3-3.

Table 3-3 Parameters Generated in Encoding Routines

Type Parameters Generated in Encoding Routine

SET {...}SEQUENCE {...}

collection of parameters generated for thecomponents

CHOICE {...} Asn_u_intx aXXXXto indicate the rank of the selected alternativeplus the collection of parameters for thecomponents

type OPTIONAL type DEFAULT value Asn_boolx pXXXXto give the presence (not null) or absence (null)of the component plus the collection ofparameters for type

BOOLEAN Asn_bool vXXXXto give the value of the boolean (0 = false,otherwise true)

INTEGER ENUMERATED Asn_int vXXXXto give the value of the integer or enumerated

BIT STRING without size limit Asn_buffer vXXXXto give the value of the bit-string; octets ofbuffer are octets of the bit-string;

--$ implement size NNNN-- BIT STRING Asn_u_intx lXXXXto give the length of the bit string (in octets)X pXXXXto give the padding of the bit string (0 to 7 bitsunused in the last octet)X * vXXXXto give the value of the bit string (pointer to thefirst octet of a contiguous array of octets)

OCTET STRING --without size limit-- Asn_buffer vXXXXto give the value of the octet string; octets of thebuffer are octets of the octet string; paddinginfo is meaningless

Page 103: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-31

3

-- $ implement size NNNN -- OCTET STRING Asn_u_intx lXXXXto give the length of the octet stringX * vXXXXto give the value of the octet string (pointer tothe first octet of a contiguous array of octets)

NULL no parameter generated

OBJECT IDENTIFIER --without size limit -- Asn_buffer vXXXXto give the contents of the object identifier;octets of the buffer are the octets of the contentspart in the encoded format

--$ implement size NNNN -- OBJECTIDENTIFIER

Asn_u_intx lXXXXto give the length of the encoded objectidentifier contentsX * vXXXXto give the contents of the octet string (pointerto the first octet of a contiguous array of octets)

REAL Asn_real vXXXXto give the value of the real

ANY Asn_buffer vXXXXto give the ASN.1 encoded representation of theactual value (in the octets of the buffer; paddinginfo is meaningless)

--$ implement entry -- type Asn_buffer vXXXXto give the ASN.1 encoded representation of thetype (result of the other routine generated forencoding the type)

Typereference if referenced type has “implement entry” formalcomment, then same as above, otherwise,parameters for the referenced type

[Class id] type[Class id] IMPLICIT type[Class id] EXPLICIT type

parameters generated for the tagged type

Table 3-3 Parameters Generated in Encoding Routines (Continued)

Type Parameters Generated in Encoding Routine

Page 104: SunLink ASN.1 Compiler User's Guide - Oracle

3-32 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Table 3-4 Parameters Generated in Decoding Routine

Type Parameters Generated in Decoding Routine

SET {...}SEQUENCE {...}

collection of parameters for the components of the setor sequence type

CHOICE {...} Asn_u_intx * aXXXXto return the rank of the effective alternative plus thecollection of parameters for the components

type OPTIONAL Asn_boolx * pXXXXto return the presence (not null) or absence (null) ofthe component plus the collection of parameters fortype

type DEFAULT value collection of parameters for type

BOOLEAN Asn_bool * vXXXXto return the value of the boolean (0 = false, otherwisetrue)

INTEGER ENUMERATED Asn_int * vXXXXto return the value of the integer or enumerated

BIT STRING--without size limit-- Asn_buffer * vXXXXto return the value of the bit-string; octets of buffer areoctets of the bit-string; buffer is allocated by thegenerated routine

--$ implement size< NNN --BIT STRING X * pXXXXto return the padding of the bit string (0 to 7 bitsunused in the last octet)Asn_u_intx * lXXXXto return the length of the bit string (in octets)X * vXXXXto return the value of the bit string (pointer to the firstoctet of a contiguous array of at least NNN octets)

OCTET STRING without size limit Asn_buffer * vXXXXto return the value of the octet string; octets of thebuffer are octets of the octet string; padding info ismeaningless; buffer is allocated by the generatedroutine

Page 105: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-33

3

--$ implement size < NNN --OCTET STRING Asn_u_intx * lXXXXto return the length of the octet stringX * vXXXXto return the value of the octet string (pointer to thefirst octet of a contiguous array of at least NNN octets)

NULL no parameter generated

OBJECT IDENTIFIER --without size limit--

Asn_buffer * vXXXXto return the contents of the object identifier; octets ofthe buffer are the octets of the contents part in theencoded format; buffer is allocated by the generatedroutine

--$ implement size NNN-- OCTET STRING Asn_u_intx * lXXXXto return the length of the encoded object identifiercontentsX * vXXXXto return the contents of the octet string (pointer to thefirst octet of a contiguous array of at least NNN octets)

REAL Asn_real * vXXXXto return the value of the real

ANY Asn_buffer * vXXXXto return the ASN.1 encoded representation of theactual value (in the octets of the buffer; padding info ismeaningless); buffer is allocated by the generatedroutine

--$ implement entry -- type

Asn_buffer vXXXXtype to give the ASN.1 encoded representation of thetype (result of the other routine generated forencoding the type)

Typereference if referenced type has “implement entry” formalcomment, then same as above, otherwise, parametersfor the referenced type

[Class id] type[Class id] IMPLICIT type[Class id] EXPLICIT type

parameters generated for the tagged type

Table 3-4 Parameters Generated in Decoding Routine (Continued)

Type Parameters Generated in Decoding Routine

Page 106: SunLink ASN.1 Compiler User's Guide - Oracle

3-34 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.2.3.1 Guidelines

The design of the generated routines for encoding and decoding the elementsof your ASN.1 description is therefore entirely based upon the locations in theASN.1 source description of the --$ implement entry -- formal comments.

In order to get a set of routines which suits the needs of your application, youshould pay attention to the following issues:

• Are all the ASN.1 types which are intended to be processed separately in theapplication associated to a generated routine for encoding/decoding?

Obviously, the first candidates for such separate processing are the ASN.1types corresponding to the different PDUs of the protocol handled by theapplication. However, depending on the organization of the softwaremodules in the application, the processing of sub-structures of these may betreated separately. Passing ASN.1 encoded buffers between the softwaremodules of the application may be a good way of keeping simple formatsfor the exchange of parameters between these modules.

• Does the number of parameters generated for the encoding/decodingroutines fit the rules imposed by the programming guide for yourapplication?

• The same question may also be applied for the length of the identifiersgenerated for the routine names and the parameters names. Note that as faras these names are directly deduced from the ASN.1 identifiers provided inthe ASN.1 source, the control is in the hands of PLC409 user.

Moreover, if some of the C identifiers which are generated do notcorrespond to any ASN.1 identifier in the description and are rathergenerated on the basis of an arbitrary number, the ASN.1 description shouldbe reviewed in order to add the missing identifiers (not mandatory inASN.1). This is a good practice in the use of PLC409.

• Are all the generated routines useful for the application? Are there be anyunused routine that could be removed by re-structuring the ASN.1description or by moving the locations of the “--$ implement entry --”directives?

• Are all the generated routines performing a job for which it is worth callingthe general encoder/decoder?

Page 107: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-35

3

For instance, if the job is limited to locating the exact alternative taken within aCHOICE type, and all the alternatives are handled by other routines, you couldsimplify the processing (i.e. through non-automatic processing).

3.2.4 Using the High-level Routines

The documentation about the generated encoded routines may be found in thegenerated listing produced by SunLink ASN.1 Compiler (xxx_prototype.hfile). This listing sums up the headers of the encoding routines, together withthe precise description of their Role, their parameters and the relation to thesource ASN.1 text.

• The encoding routines make no check of the consistency of the parametersprovided as input. This implies that the encoding routines do not return anystatus result. They act as procedures and not as functions.

However, they are not declared as functions returning void , because ofportability problems with the void facility. They are rather declared asfunctions with no specific type returned. The generated encoded routineshall not be called by:

nor by:

but simply by:

• In the case where the C programming environment supports theprototyping facility, the generation listing (xxx_prototype.h file) may beused as the file containing the prototypes of the generated routines.

if (Cmy_routine(.....))

result = Cmy_routine(...);

Cmy_routine(....);

Page 108: SunLink ASN.1 Compiler User's Guide - Oracle

3-36 SunLink ASN.1 Compiler User’s Guide—August 1994

3

In the simple case (without prototyping), the external declarations couldsimply be done as follows:

• The input parameters provided to the encoding routines are always passed“by value” (as opposed to the parameter for the result buffer, which ispassed “by reference” the address of this parameter must be provided).

This means that if the header of the generated routine is the following one:

The local variables of the application are as follows:

external Cmy_routine_A();external Cmy_routine-B();........{....Cmy_routine_A(.....);....Cmy_routine_B(.....);....}

Cmy_routine (va, lb, vb, oc, vc, res_buf) Asn_bool va; Asn_u_intx lb; X * vb; Asn_boolx oc; Asn_int vc; Asn_buffer * res_buf;

X array[14];short present_c;asnsvsint value_c;Asn_buffer res_buf;

Page 109: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-37

3

The routine should be called as follows:

• The parameters which correspond to alternatives of a CHOICE type or toASN.1 elements which are OPTIONAL or have a DEFAULT value are onlytaken into account by the routine when necessary (i.e. when the alternativeis the effective one or when the element is declared present).

However, some value with the appropriate type must be provided for suchparameters in any case. Use of variable number of parameters in C will alwayslead to troubles. A dummy value is the best answer to such issue.

• The parameters are processed from last to first (backwards processing ofASN.1 components). As the processing of an encoding routine should not beinterrupted, this is not visible from the calling application.

• The input buffers, if any, to the encoding routines are used by the encoder toform the resulting ASN.1 encoded buffer. This means that the applicationshall not use these buffers after the call to the encoding routine, and thebuffer pointer shall be considered as no longer valid.

• The two last points also imply that the same buffer cannot be provided fortwo parameters of the same call to an encoding routine, unless theseparameters are significant in cases which are always exclusive (e.g. whenthey correspond to alternatives of a same CHOICE).

resbuf = (Asn_buffer) 0;Cmyroutine(

(Asn_bool) 1,/* literal values must be typecasted */(Asn_u_intx) 10,&(array[0]),/* arrays must be exact expected type*/(Asn_boolx)present_c,/* variables with a different

*//* type must be typecasted */

value_c, /* variables with the exact same type*//* do not need tp be typecasted */

&(resbuf) /*result buffermust be exact *//* Asn_buffer variable and, its*//* address must be passed */

);

Page 110: SunLink ASN.1 Compiler User's Guide - Oracle

3-38 SunLink ASN.1 Compiler User’s Guide—August 1994

3

• Also as a consequence from the previous points, the application should takecare that a buffer may be lost if not used by the encoding routine. This mayhappen if the buffer is passed, but the parameter is declared as absent(because the presence/absence associated boolean parameter is null).

• The result of the encoding is stored in the buffer variable whose address ispassed to the encoding routine. The original value of this buffer variablemust be a valid value for a buffer pointer (generally a null buffer pointer(i.e. "(Asn_buffer) 0 " ).

• The storage for the ASN.1 encoded octets is allocated by the routine, withthe help of the scpbuf() buffer manipulation primitive.

This means that if you want the routine to create a new buffer, you mustdefine a Asn_buffer variable and initialize it as follows :

and the primitive must be called by:

Conversely, if the buffer variable in which the result will be stored is a non-null buffer, this buffer will be extended on its left, and the newly encodedoctets will be pre-append to the original contents of the buffer.

If it is desirable to have the encoding routine concatenate the newly encodedvalue to an existing buffer, declare as follows:

where last_partbuffer has been created previously by another encoding.

After which my_result_buffer contains a concatenation of:• the new octets (at the beginning)• the contents of the last_part_buffer (at the end)

my_result_buffer = (Asn_buffer) 0 ;

Cmy_primitive (....., &(my_result_buffer));

my_result_buffer = last_partbuffer;Cmy_primitive ( ..... , &(my_result_buffer));

Page 111: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-39

3

This feature is very useful when encoding elements of SET OF orSEQUENCE OF.

3.2.4.1 Calling Decoding Routines

The following points should be taken into account when calling the decodingroutines:

1. The decoding routines check the input ASN.1 encoded octets (contained bythe input buffer), with respect to:• the Basic Encoding Rules for ASN.1• the part of the ASN.1 description which corresponds to the decoding

routine

This means that the decoding routines act as functions and always return astatus which indicates their success (null returned value) or failure (non-nullreturned value). Take care that this status is not of the simple “int” type, butof the “Asn_u_intx” customizable type.

The generated decoded routine shall not be called by:

but by:

my_buffer = 0while(ElementOfTheListToEncode); { /* encode one more element of the list */ Cmy_elem ( ........&(my_buffer)); }my_final_buffer = 0Cmy_set(my_buffer, &(my_final_buffer));

Dmy_routine(....)

if (Dmy_routine(.....))

Page 112: SunLink ASN.1 Compiler User's Guide - Oracle

3-40 SunLink ASN.1 Compiler User’s Guide—August 1994

3

or by:

2. It is a good practice to give an “external... ” declaration of the generateddecoding routines used by a module at the beginning of this module.

In the case where the C programming environment supports theprototyping facility, the generation listing (xxx_prototype.h file) may beused as the file containing the prototypes of the generated routines.

In the simple case (without prototyping), the external declarations couldsimply be done as follows:

3. All the parameters (input and output) provided to the decoding routines arealways passed “by reference” (i.e. by providing their address).

The application should take care that the input buffer is passed by reference,because it is truncated by the decoding routine. Moreover, due to thetransfer “by reference”, literal values cannot be accepted when callingdecoding routines.

To remain portable, the the C types for these parameters must be declaredtypes.

result = Dmy_routine(...);

external Asn_u_intx Dmy_routine_A();external Asn_u_intx Dmy_routine_B();........{....if (Dmy_routine_A(.....)) ....;....success = Dmy_routine_B(.....);....}

Page 113: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-41

3

This means that if the header of the generated routine is the following one:

All local variables of the application are:

The routine should be called as follows:

Dmy_routine (buffer, va, lb, vb, oc, vc)Asn_buffer * buffer;Asn_bool * va;Asn_u_intx * lb;X * vb;Asn_boolx * oc;Asn_int * vc;

Asn_bool value_a;Asn_u_intx leng_b;X array[14];Asn_boolx present_c;Asn_int value_c;

if (Dmyroutine (&(resbuf),/* address must be passed also for */

/* input buffer */&(value_a),/* for the output parameters, only */

/* this form of programming is */&(leng_b),/* recommended : */&(array[0]),/* - no typecasts */&(present_c),/* - no tricks */&(value_c)/* otherwise: trouble */

)){/* error case */...}else{/* normal case */...}

Page 114: SunLink ASN.1 Compiler User's Guide - Oracle

3-42 SunLink ASN.1 Compiler User’s Guide—August 1994

3

4. The parameters are processed from first to last (forward processing ofASN.1 components). Unlike in the encoding phase, the processing of adecoding routine may be interrupted in case of error, and should be takeninto account by the calling application.

5. The ASN.1 encoded buffer provided as input to the decoding routine is usedin order to form the resulting decoded buffers. This means that theapplication shall not expect the input buffer to continue to contain the sameoctets.

The resulting value for the input buffer is the octets which have not beenprocessed by the decoder, i.e.:

• either the remaining octets from the top-level ASN.1 encoded Header-Length-Contents whose processing was interrupted by an error,

• or the trailing octets from the original buffer that came after the successfullydecoded top-level Header-Length-Contents.

• if all the input buffer has been decoded, it will be set to the null buffer onreturn.

6. The storage for the returned buffers, if any, is allocated by the decodingroutine, by fragmenting the input buffer.

However, there is no requirement on the original values of the variableswhose addresses are passed to the decoding function.

The fact that the resulting value for the input buffer is the trailing octetsfrom the original buffer that came after the successfully decoded top-levelHeader-Length-Contents allows you to decode “SET OF” or“SEQUENCE OF” elements:

my_buffer = 0/* decode the set/sequence of*/if (Dmy_se(&my_buffer_to_decode,&my_buffer))

{ /* decoding error */ }/* decode the elements of the set/sequence of */while (my_buffer);

{/* still some elements to decode */if (Dmy_elem (&my_buffer,.......)

{ /* decoding error */ }}

Page 115: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-43

3

3.2.5 Compiling and Linking

The following C modules are involved in the compilation of an applicationusing the high-level generated routines:

• the modules of the application

• the modules containing the generated routines

• the modules of the general encoder/decoder

• the modules of the memory management package

These modules may use some of the include files which are generated by theSunLink ASN.1 Compiler. The dependences are described by Table 3-5.

3.2.5.1 Compiler Generated Files

When generating output sources, the SunLink ASN.1 Compiler produces filesused for both the High Level and the Symmetric Low Level.

When using the high level access method, the following files are generated:

XXX_encode.c (encoding routine declarations)This file must be compiled and linked to the application.

Table 3-5 Dependencies Between Sources and Includes

Include Files

Source Files Application Generated GeneralBuffer

Management

Application Source YES NO YES YES

GeneratedRoutines

NO YES YES YES

GeneralEncoder/Decoder

NO NO YES YES

BufferManagement

NO NO NO YES

Page 116: SunLink ASN.1 Compiler User's Guide - Oracle

3-44 SunLink ASN.1 Compiler User’s Guide—August 1994

3

XXX_decode.c (decoding routine declarations)This file must be compiled and linked to the application.

XXX_enc_matrix.h (encoding matrix)This file is included in XXX_encode.c.

XXX_dec_matrix.h (decoding matrix and associated data)This file is included in XXX_decode.c.

XXX_prototype.h (file containing the prototype of the generatedfunctions)This file can be included in the application program if prototyping issupported by the C compiler.

Page 117: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-45

3

3.3 Using The Symmetric Low Level AccessYou can also access the SunLink ASN.1 programming environment via twogeneral routines (one to encode and one to decode), that give pointers tostructures generated by the SunLink ASN.1 Compiler based on the ASN.1description and filled in by the application. This is called the symmetric low levelaccess method.

3.3.1 Generating Structures

When you specify the C output language (-ln C option) the SunLink ASN.1Compiler automatically generates structures (xxx_types.h file) which are thetranslation of the ASN.1 types into their equivalents in the C language.

For example, from the following ASN.1 definition:

MODULE DEFINITIONS ::=BEGIN

T ::= SEQUENCE {vint INTEGER,voct OCTET STRING,vty T1};

T1 ::= SEQUENCE {vintbis INTEGER,voctbis OCTET STRING}

END

Page 118: SunLink ASN.1 Compiler User's Guide - Oracle

3-46 SunLink ASN.1 Compiler User’s Guide—August 1994

3

the SunLink ASN.1 Compiler generates the following C structures:

These structures will be the basis of the exchanges between the generalencoding/decoding motor and the application.

While the structures are deduced from the ASN.1 description, this generationmay be controlled by formal comments “--$ implement entry --” (see Section 2.8,“Formal Comments,” on page 2-25). The "--$ implement entry --” formalcomment allow you to perform partial encoding/decoding.

For our example, we may decide not to encode/decode T1 whileencoding/decoding T but to do it previously (if we perform encoding) or later(if we perform decoding). In order to achieve this, we have to mention in ourdescription that T1 is a particular entry:

typedef/*# 3 */ struct _Ts_3 {/*# 1 */ Asn_int vintbis;/*# 2 */ Asn_buffer voctbis; } T1;

typedef/*# 7 */ struct _Ts_7 {/*# 4 */ Asn_int vint;/*# 5 */ Asn_buffer voct;/*# 6 */ T1 vty; } T;

MODULE DEFINITIONS ::=BEGIN

T ::= SEQUENCE {vint INTEGER,voct OCTET STRING,vty T1};

T1 ::= --$ implement entry - - SEQUENCE {vintbis INTEGER,voctbis OCTET STRING}

END

Page 119: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-47

3

The resulting T structure takes account of the inserted Formal comment.Instead of the expanded values of T1, it is the ASN.1 form (T1) which isexpected, as shown:

Thus, instead of having one single call to the encoding/decoding motorfor the main type, with the following structure:

T structure:

• value of vint• value of voct• value of vintbis• value of voctbis

Adding the extra “implement entry” (in bold) as above, allow you to call theencoding/decoding motor twice, with the following structure:

T1 structure:

• value of vintbis• value of voctbis

T structure:

• value of vint• value of voct• value of the ASN.1 encoding of T1

typedef/*# 3 */ struct _Ts_3 {/*# 1 */ Asn_int vintbis;/*# 2 */ Asn_buffer voctbis; } T1;

typedef/*# 7 */ struct _Ts_7 {/*# 4 */ Asn_int vint;/*# 5 */ Asn_buffer voct;/*# 6 */ Asn_buffer vty; } T;

Page 120: SunLink ASN.1 Compiler User's Guide - Oracle

3-48 SunLink ASN.1 Compiler User’s Guide—August 1994

3

By inserting additional “implement entry” comments, the user will get a set ofstructures which is adequate for his application.The main criteria for the use ofthe --$ implement entry -- formal comment specification is how it fits thearchitecture of the PLC409 user application in terms of module organizationand information flow.

3.3.1.1 Generation Rules

The correspondence between the nature of the component and the C type ofthe structure field is given in Table 3-6.

Table 3-6 Generated Types for Low Level Access

Type Parameters Generated in the Structures

SET {...}SEQUENCE {...}

collection of fields for the components

SET OF{}SEQUENCE OF{}

pointer to a list of substructures

CHOICE {...} Asn_u_intx aXXXXto give the rank of the effective alternative plus thecollection of parameters for the components

type OPTIONAL type DEFAULT value Asn_boolx pXXXXto give the presence (not null) or absence (null) of thecomponent plus collection of parameters for type

BOOLEAN Asn_bool vXXXXto give the value of the boolean (0 = false, otherwisetrue)

INTEGER ENUMERATED Asn_int vXXXXto give the value of the integer or enumerated

BIT STRING without size limit Asn_buffer vXXXXto give the value of the bit-string; octets of buffer areoctets of the bit-string;

--$ implement size < NNNN BIT STRING X pXXXXto give the padding of the bit string (0 to 7 bits unusedin the last octet)Asn_u_intx lXXXXto give the length of the bit string (in octets)X vXXXX[NNNN-1]to give the value of the bit string

Page 121: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-49

3

OCTET STRING without size limit Asn_buffer vXXXXto give the value of the octet string; octets of the bufferare octets of the octet string; padding info ismeaningless

-- $implement size;NNNN --OCTET STRING Asn_u_intx lXXXXto give the length of the octet stringX vXXXX[NNNN-1]to give the value of the octet string

NULL no parameter generated

OBJECT IDENTIFIER without size limit Asn_buffer vXXXXto give the contents of the object identifier; octets ofthe buffer are the octets of the contents part in theencoded format

--$ implement size NNNN -- OBJECT IDENTIFIER Asn_u_intx lXXXXto give the length of the encoded object identifiercontentsX vXXXX[NNNN-1]to give the contents of the octet string

REAL Asn_real vXXXXto give the value of the real

ANY Asn_buffer vXXXXto give the ASN.1 encoded representation of the actualvalue (in the octets of the buffer; padding info ismeaningless)

Typereference if referenced type has implement entry formalcomment, then same as below, otherwise, parametersfor the referenced type

--$ implement entry -- Asn_buffer vXXXXto give the ASN.1 encoded representation of the actualvalue (in the octets of the buffer) of the type to whichthis formal comment is attached

[Class id] type[Class id] IMPLICIT type[Class id] EXPLICIT type

parameters generated for the tagged type

Table 3-6 Generated Types for Low Level Access (Continued)

Type Parameters Generated in the Structures

Page 122: SunLink ASN.1 Compiler User's Guide - Oracle

3-50 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.3.2 Structure Identifiers

When generating the set of C structures, the compiler also generates a set ofstructure identifiers. One identifier is generated for each element of thedescription. When using the symmetric low level access, the useful identifiersare those which correspond to the top level messages.

For example, from the following ASN.1 definition:

the SunLink ASN.1 Compiler generates the following structure:

and this set of identifiers:

The useful identifier is Tr_DD: it identifies the structure DD, which correspondsto the declaration of DD in the ASN.1 description.

MODULE DEFINITIONS ::=BEGIN

DD ::= SEQUENCE {vint INTEGER,voct OCTET STRING,vseqof SEQUENCE OF INTEGER}

END

typedef/*# 5 */ struct _Ts_5 {/*# 1 */ Asn_int vint;/*# 2 */ Asn_buffer voct;/*# 4 */ struct _Ts_4 { struct _Ts_4 *asnnext;/*# 3 */ Asn_int asnvalue; } * vseqof; } DD;

#define Tr_iE1 3#define Tr_DD 6

Page 123: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-51

3

3.3.3 Calling the Encoding Routine

To encode an ASN.1 message, the user must fill the structure corresponding tothe message before calling the general encoding routine. Each field of thestructure must contain the value to be encoded.

The information expected by the general encoding routine are:

• a pointer which addresses the initialized structure

• the identifier of the given structure (chosen from the set of structureidentifiers)

• the encoding and decoding matrices (generated by the SunLink ASN.1Compiler and initialized)

According to this information, the general encoding routine will return theequivalent ASN.1 encoded form of the given structure.

For the purpose of this example, suppose that the message to encode iscomposed of:

• vint equals 3,• voct equals “test”,• vseqof equals {4, 5}

In the program, the user must declare a variable of type is DD.

He has then to fill his variable with the correct values:

DD vT;

/* INTEGER */vT.vint =3;

/* OCTET STRING */ASN_BUF_NEW(vT.voct,4);ASN_BUF_WRITE(vT.voct,”test”,4);

/* SEQUENCE OF INTEGERS */vT.vseqof = malloc(sizeof(structV_Ts_4));vT.vseqof->asnvalue = 4;vT.vseqof->asnnext = malloc(sizeof(structV_Ts_4));vT.vseqof->asnnext->asnvalue = 5;vT.vseqof->asnnext->asnnext = 0;

Page 124: SunLink ASN.1 Compiler User's Guide - Oracle

3-52 SunLink ASN.1 Compiler User’s Guide—August 1994

3

The user can now invoke the general encoder (asn_encod() function), giving:

• the encoding matrix

• the decoding matrix

• the identifier of the structure

• the pointer to the structure

• a null buffer which will be updated.

As the motor is encoding the message, it automatically makes some updates tothe structure:

• when a buffer is given (translation of ANY, OCTET STRING, BIT STRING ,...)inside a structure, the field is updated to null.

• when a chained list is given (translation of a SEQUENCE OF or SET OF), thelist is cleaned.

In order to do this, the encoder calls the asn_freemem() routine, giving apointer to be released and the size of the block to be released. Theasn_freemem() function must be customized by the user.

In the example, as the elements of the SEQUENCE OF are obtained by a call tomalloc() , the asn_freemem() function must call the free() function. Theequivalent customization is:

/* ENCODER CALL */Asn_buffer result = 0;

asn_encode(xxx_encode_matrix,xxx_decode_matrix,Tr_DD,&vT,&result);

asn_freemem(p_p_area,size)A * p_p_area;Asn_u_intx size;{

free(*p_p_area);*p_p_area = 0;

}

Page 125: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-53

3

Figure 3-2 Management of the Memory During Encoding

In the example, yyyy is a pointer to a list of integers (for example aSEQUENCE OF INTEGER). asn_freemem is called once for every element inthe list, starting with the last element in the list.

GENERAL ENCODER

ptr

3xxxxyyyy

tttt4

05

buffer = ”test”

buf = 0

05

04

first call toasn_freemem

second call toasn_freemem

ptr

300

buf buffer = the asn1 encoded message

Page 126: SunLink ASN.1 Compiler User's Guide - Oracle

3-54 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Nameasn_encode

ClassDefined as a function in the file asn1_runtime.h .

Format

RoleGeneral encoding function used for symmetric low level access.

Used byUser application

Input Parametersmatcod: Encoding matrix generated by the SunLink ASN.1 Compiler.

matdec: Decoding matrix generated by the SunLink ASN.1 Compiler.

strid: Structure identifier.This identifier is a pseudo constant generated by the SunLink ASN.1Compiler. For an input ASN.1 text, a complete file of identifiers isgenerated by the compiler. Each of them corresponds to acomponent of the description.

str: Pointer to the structure to encode.This structure has been previously filled by the user.

Output Parametersasn: Equivalent ASN.1 form of the given structure

asn_encode(matcod, matdec, strid, str, asn)Asn_encode_mtx matcod;Asn_decode_mtx matdec;Asn_u_intx strid;Char * str;Asn_buffer * asn;

Page 127: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-55

3

Nameasn_freemem

ClassDefined as a function in the file asn1_runtime.h .

Format

RoleRelease memory back to the user.

Caution – If this function is not customized, a warning message is printed atruntime by the general encoder, when SEQUENCE OF and SET OF syntaxesare used.

Used byProgramming environment

Input Parametersp_p_area: Address of pointer to be updated.

size: Size previously allocated

Output Parameters*p_p_area: Must be updated to 0;

asn_freemem(p_p_area,size)

Char ** p_p_area;Asn_u_intx size;

!

Page 128: SunLink ASN.1 Compiler User's Guide - Oracle

3-56 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.3.4 Calling the Decoding Routine

To decode a message, the user calls the decoding routine, giving the ASN.1message to decode and a pointer to a structure where the decoded values arestored.

The information expected by the general decoding routine is:

• a pointer which addresses the structure to update

• the identifier of the given structure (chosen from the set of structureidentifiers)

• the encoding and decoding matrixes (generated by the SunLink ASN.1Compiler and initialized)

According to this information, the general decoding routine will return thefilled structure.

It must be noted that the structure given to the routine has to be reset (i.e., allthe fields have to be null). An easy way to do this is to update the structurewith 0s:

In order to decode the message, the user has to declare a variable whose typeis DD. (See the above example.) Let us call it vTT.

You have to enter your variable with 0s:

VVT pt;Asn_bool * fi;int i;for (i=0, fi = &pt; i< sizeof(VVT) ; i++ ) *(fi+i )= 0;

DD vTT;

for (i=0, fi = &vTT; i< sizeof(DD) ; i++ ) *(fi+i )= 0;

Page 129: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-57

3

The user can now invoke the general decoder (asn_decode() function),giving:

• the encoding matrix (output by the compiler in the fileXXX_enc_matrix.h )

• the decoding matrix (output by the compiler in the fileXXX_dec_matrix.h )

• the identifier of the structure (a set of identifiers in the fileXXX_type_ids.h )

• the buffer to decode

• the pointer on the structure

As the decoder is decoding the message, it automatically makes some updatesto the structure:

• All the fields corresponding to basic types are updated.

• All the buffers are created.

• When a list of elements is present in the structure (representation of aSEQUENCE OF or SET OF), the general decoding routine builds the chainedlist according to the values contained in the message. In order to getmemory, it calls the asn_allocmem() function. The asn_allocmem()function must be customized by the user.

For example,

/* CALL TO DECODER */

asn_decode(xxx_encode_matrix,xxx_decode_matrix,tr_DD,&buffer,&vTT);

Asn_u_intx asn_allocmem(p_p_area,size)Char ** p_p_area;Asn_u_intx size;{*p_p_area = calloc(size, 1)return ((*p_p_area) ? 0 : 1 );}

Page 130: SunLink ASN.1 Compiler User's Guide - Oracle

3-58 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Figure 3-3 Management of the Memory During Decoding

In the example, yyyy is a pointer to a list of integers (representing aSEQUENCE OF INTEGER, for example). asn_allocmem is called once forevery element in the list, starting with the last element in the list. In theexample, the list contains two integers, 4 and 5.

GENERAL DECODER

ptr

3xxxxyyyy

ttt4

05

buffer = ”test”

buf = 0

000000

first call toasn_allocmem

second call toasn_allocmem

ptr

000000000000000

buf buffer = the asn1 encoded message

000000

Page 131: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-59

3

Nameasn_allocmem

ClassDefined as a function in the file asn1_runtime.h .

Format

Used byProgramming environment.

Caution – If this function is not customized, a warning message is printed atruntime by the general encoder, when SEQUENCE OF and SET OF syntaxesare used.

RoleRequests memory from the user.

Input Parameterssize: Size needed in octets

Output Parameters*p_p_area: *p_p_area must address the allocated area

This area must be filled with zeros.

Return• 0 if allocation succeeds

• not 0 otherwise

Asn_u_intx asn_allocmem(p_p_area,size)

A * p_p_area;Asn_u_intx size;

!

Page 132: SunLink ASN.1 Compiler User's Guide - Oracle

3-60 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Nameasn_decode

ClassDefined as a function in the file asn1_runtime.h .

Format

RoleDecode an ASN.1 form and fill the result in a given structure.

Used byUser application

Input Parametersmatcod: Encoding matrix generated by the compiler

matdec: Decoding matrix generated by the compiler

strid: Structure identifierThis identifier is a pseudo constant generated by the PLC409. For aninput ASN.1 text, a complete file of identifiers is generated by thecompiler. Each of them corresponds to a component of thedescription. The user has to give the identifier which corresponds tothe component to decode.

asn: ASN.1 encoded form of the given structure

str: Pointer to the structure to update

Asn_u_intx asn_decode(matcod, matdec, strid, asn, str)

Asn_encode_mtx matcod;Asn_decode_mtx matdec;Asn_u_intx strid;Asn_buffer *asn;Char str;

Page 133: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-61

3

Output Parameters*str: Updated structure

ConstraintsCaller must ensure that each time this primitive is used the structure to updateis empty (i.e.: filled with null values).

Return

• 0 if decoding operation succeeds

• an error code if decoding operation fails (See Section 3.6.1, “ErrorDetection,” on page 3-79.)

Page 134: SunLink ASN.1 Compiler User's Guide - Oracle

3-62 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.3.5 Offset Initialization

When using symmetric low level access, the general engines have to read/fillfields within a structure. In order to reach any wanted field, the engines readinformation in the encoding and decoding matrix that represent the offset toskip from the beginning of the structure. As these offsets are dependant on themachine on which the encoder/decoder engines are used, the offsetinformation can not be put in the matrix at generation time.

Warning – When using the symmetric low-level access, the encoding anddecoding matrices generated by the SunLink ASN.1 Compiler need to becompleted according to the target machine.

To complete the matrix, at initialization time, call a function generated bythe SunLink ASN.1 Compiler. In order to do this, include a file called“xxx_fill_matrix.h ” (suppose that the ASN.1 input text is called“xxx.X409 ”) in the application program. This include file contains afunction called “xxx_fill_matrix() ” which has to be called before anyof the encoder/decoder functions.

3.3.6 Compiling and Linking

The C modules involved in the compilation of an application making use of theSymmetric Low-Level are the following:

• the modules of the application

• the modules of the general encoder/decoder

• the modules of the memory management package

Page 135: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-63

3

These modules may use some of the include files which are generated by theCompiler. The dependencies are described by Table 3-7 on page 3-63.

3.3.7 Compiler Generated Files

When generating C sources, the SunLink ASN.1 Compiler produces files usedfor both high level and symmetric low level access.

When using the symmetric low level, the following files are useful:

XXX_types.h (file containing the generated C structures)This file must be included in the application program.

XXX_type_ids.h (file containing the references to the C structures)This file must be included in the application program.

XXX_dec_matrix.h (decoding matrix and associated data)This file must be included in the application program.

XXX_enc_matrix.h (encoding matrix)This file must be included in the application program.

XXX_fill_matrix.h (file containing the functions used to complete thematrix )This file has to be included in the application program.

Table 3-7 Dependencies Between Sources and Includes

Include FilesSource Files Application

CompilerGenerated

CompilerGeneral

BufferManagement

Application Source YES YES YES YES

GeneralEncoder/Decoder

NO NO YES YES

Buffer Management NO NO NO YES

Page 136: SunLink ASN.1 Compiler User's Guide - Oracle

3-64 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.3.8 Include Order

When using the symmetric low level access, you must include some generatedfiles in his application program in order to be able to call the generalencoding/decoding engine. Some order must be respected when includingthese files, the order should be:

/*-- ASN.1 runtime --*/#include “asn1_runtime.h”

/*-- Generated structures --*/#include “XXX_types.h”

/*-- Generated references --*/#include “XXX_type_ids.h”

/*-- Generated information base --*/#include “XXX_enc_matrix.h”#include “XXX_dec_matrix.h”

/*-- Generated function : offset computation --*/#include “XXX_fill_matrix.h”

Page 137: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-65

3

3.4 Object Identifier ValuesAn object identifier is used to convey a reference. For an application, the formof the object identifier does not matter.

In the SunLink ASN.1 encoder/decoder implementation, whenever an objectidentifier is needed, it is its encoded content which is exchanged between theuser application and the encoder/decoder. It is assumed that the applicationmanipulates the encoded content of object identifiers directly. Working directlywith encoded contents of object identifiers saves time: the time toencode/decode the content of these object identifiers.

In spite of this performance gain, some applications prefer to work with thedecoded content of object identifiers. Therefore, the programming environmentalso contains two routines which are usedto encode/decode the contents of anobject identifier:

Nameasn_decode_oid

ClassDefined as a function in the file asn1_runtime.h .

Format

RoleTranslates an object identifier described in an ASN.1 encoded form into its Cstring form.

Used byUser application

asn_decode_oid(buf, strg)

Asn_buffer * buf;Char * strg;

Page 138: SunLink ASN.1 Compiler User's Guide - Oracle

3-66 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Input Parametersbuf: Encoded form of the value of the object identifier.

strg: A pointer onto a memory area where to decode the object identifier.

Output Parametersstrg: The area is filled with the decoded form of the object identifier.

where xi is a number.

Return• 0 if success

• not 0 if failure

Example

{ x1 x2 x3 x4 ...... xj }

Asn_bool memo[128];if (asn_decode_oid(&buf1,memo))

printf(“ invalid object identifier “);

Page 139: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-67

3

Nameasn_encode_oid

ClassDefined as a function in the file asn1_runtime.h .

Format

RoleTranslates an object identifier described as a C string into the ASN.1 equivalentencoded value (without its length or tag) expected by the ASN.1 encoder.

Used byUser application.

Input Parametersstrg: C string form of the object identifier

where xi is a number.

Output Parameters*buf: Pointer to buffer of type Asn_buffer containing the encodedASN.1 value.

asn_encode_oid(strg, buf)

Char * strg;Asn_buffer * buf;

{ x1 x2 x3 x4 ...... xj }

Page 140: SunLink ASN.1 Compiler User's Guide - Oracle

3-68 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Return• 0 if success

• not 0 otherwise

Example

Asn_buffer buf1;if (asn_encode_oid(“{ 1 2 34 56 }”,&buf1))

printf(“ invalid object identifier “);

Page 141: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-69

3

3.5 Advanced Use of the SunLink ASN.1 CompilerGenerally, applications which use the ASN.1 decoding facilities have someprocessing to do on the decoded values. One of the jobs is to examine thevarious decoded values in order to check their validity. If one of the values iswrong, all the decoded message is considered wrong.

The --$ exit XX -- formal comments have been introduced in order toperform some actions (control for example) during the ASN.1 decoding.

Example:

Suppose that an application conveys a lot of “OBJECT IDENTIFIER ” types. Inits ASN.1 description, this type appears in the definition of various other types.Whenever an OBJECT IDENTIFIER is decoded, suppose that the applicationwants to be sure that the value of the OBJECT IDENTIFIER is registered inone of its databases.

ASN.1 definition:

In order to check the object identifiers when processing a messagecorresponding to the type T, the user must normally:

1. invoke the decoder in order to decode the type T

2. after the complete decoding, call a routine for each of the OBJECTIDENTIFIER values (fields a and d) contained in the message, to check itsvalidity versus the database.

The exit routine mechanism allow you to do this repetitive action during theASN.1 decoding.

M DEFINITIONS ::=BEGIN

..........T ::= SEQUENCE{

a OB,b INTEGER,c OCTET STRING,d OB};

OB ::= OBJECT IDENTIFIER ;END

Page 142: SunLink ASN.1 Compiler User's Guide - Oracle

3-70 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.5.1 Principles

Whenever a --$ exit xx -- formal comment (where xx is a positivenumber) is associated to a type, the decoding motor invokes a special function(called asn_exit() ) immediately after having achieved the decoding of anycomponent with that given type, and before proceeding to the next componentto decode.

Such a special function is invoked with the following parameters:

• the pointer to the decoded value for the component

• an integer which corresponds to the number attached to the exit (i.e. the xxnumber which was specified in the --$ exit xx -- formal comment)

• with the index within the generated matrix where the concerned componentis described (parameter “line”)

This index is not generally useful, unless the same exit number has beenspecified for different occurrences of the --$exit xx -- formal comment. Insuch situations, the index provided as the line parameter can serve todistinguish between the various occurrences of the same exit.

3.5.2 Routine Description

The asn_exit() routine has the following interface:

This routine is declared in the source file asn1_runtime.h and must bemodified by the user when the exit routine facility is used to incorporate theadditional verifications which are wanted.

The routine must return:

• 0 if exit operation succeeds.

The additional verifications performed by the exit routine have succeededand returned an ok status.

Asn_u_intxasn_exit (num, ptr, line)Asn_intx num ;char * ptr;Asn_u_intx line;

Page 143: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-71

3

In this case, the decoding engine then resumes its decoding process.

• non null value if operation fails.

The additional verifications performed by the exit routine failed.

The decoding engine then immediately stops its processing and returns adecoding error (giving the reason “bad return from the exit routine”)

In our example, a possible implementation of the asn_exit() routine couldbe:

where myroutine() is the function which checks the value of an ObjectIdentifier.

In this particular case, the utility of the --$ exit ... -- formal commentis two-fold:

• It reduces the size of the application code: the verification of ObjectIdentifier values can be processed for every Object Identifier componentwithout requiring more code in the application.

• It reduces the time of processing: whenever an incorrect Object Identifiervalue is encountered, the decoding process is stopped before the end of theASN.1 message. The processing of such error cases is also unified with thegeneral processing of decoding errors.

{switch (a)

{.....case 339 :

/* some object identifier to check */if (myroutine(*((Asn_buffer *)b)))

return 0;else

return 1;break;

.......}

)asn_exit(a,b,c)

Page 144: SunLink ASN.1 Compiler User's Guide - Oracle

3-72 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.5.3 Decoded Value

When the asn_exit() routine is invoked, the second argument is a pointer tothe decoded value for the concerned component.

The type of this decoded value depends on:

• the nature of the ASN.1 type corresponding to the value

• the various formal comments associated to that type

The various correspondences between the ASN.1 types and types of pointercan be deduced from the rules described in Section 3.3.1.1, “Generation Rules,”on page 3-48.

Example 1

The pointer is a pointer to a Asn_buffer

Example 2

The pointer is a pointer to the structure:

--$ exit 3 -- GraphicString

--$ exit 3 -- -- $ implement size < 4 -- BIT STRING

struct{Asn_u_intx asnlength;X asnpadding;X asnvalue[3];};

Page 145: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-73

3

Example 3

The pointer is a pointer to an Asn_int .

3.5.4 Application Packages

The declaration of packages is a facility offered by the compiler in order togenerate less information when the application is cut into parts.

As input, the ASN.1 definition consists of some ASN.1 modules, the compilergenerates all the information and interfaces needed in order to manipulateevery element of the description.

Consider the following example:

An application has to deal with ASN.1 types which are derived from the type“Person” as described below.

--$ exit 3 -- INTEGER

A DEFINITIONS ::=BEGIN

EXPORTS Person;Person ::= --$ implement entry -- SEQUENCE

{name OCTET STRING,age INTEGER}

END

B DEFINITIONS ::=BEGIN

IMPORTS Person FROM A;Couple ::= --$ implement entry -- SET

{man [1] Person,woman[2] Person}

END

Page 146: SunLink ASN.1 Compiler User's Guide - Oracle

3-74 SunLink ASN.1 Compiler User’s Guide—August 1994

3

A possible way to implement such an application could clearly be to divide itinto two parts:

• the first one processes the ASN.1 type Couple.

• the second one processes the ASN.1 type Employee.

If the ASN.1 modules are compiled together, the information generated allowsthe manipulation of:

• the common types (defined in A)

• the types defined in module B

• the types defined in module C

through a single set of data and functions.

If for some packaging reasons (depending on the design of the application), thefirst and second parts have to be independent, (module B and C areindependent from an ASN.1 point of view and can therefore be compiledseparately), the application, cut into two parts, has to manipulate two sets ofdata and functions:

1. the first set contains all the data and functions necessary to process:• the common types (module A)• the useful types of module B

C DEFINITIONS ::=BEGIN

IMPORTS Person FROM A;Employee ::= --$ implement entry -- SET

{identity Person,number INTEGER}

END

Page 147: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-75

3

The ASN.1 modules used during the first compilation are therefore:

2. the second set contains all the data and functions necessary to process:• the common types (module A)• the useful types for the module C

Thus the ASN.1 modules used during the second compilation are:

A DEFINITIONS ::=BEGINEXPORTS Person;Person ::= --$ implement entry -- SEQUENCE

{name OCTET STRING,age INTEGER}

END

B DEFINITIONS ::=BEGINIMPORTS Person FROM A;Couple ::= --$ implement entry -- SET

{man [1] Person,woman [2] Person}

END

A DEFINITIONS ::=BEGINEXPORTS Person;Person ::= --$ implement entry -- SEQUENCE

{name OCTET STRING,age INTEGER}

END

Page 148: SunLink ASN.1 Compiler User's Guide - Oracle

3-76 SunLink ASN.1 Compiler User’s Guide—August 1994

3

The result of such manipulation is that all the information concerning thecommon types (Person) is generated twice.

The packages facility is intended to avoid such problems.

3.5.5 Principles

The package declaration allows you to specify to the compiler that somedefined ASN.1 types do not have to generate information. They are present inthe description in order to permit the ASN.1 validation but no associated datahave to be generated. It is supposed that the appropriate processing of thesetypes (encoding and decoding) is done elsewhere.

The way to indicate some packages to the compiler is to specify, whenimplementing the --$ implement entry -- formal comments, a numberwhich refers to a package number:

The package number must respect the constraint that it be between 1 and 49.

When compiling the description, the user must specify which packages have tobe generated. In order to achieve that, he has to add the -nty nn option(where nn is the package number) when invoking the SunLink ASN.1Compiler using the general command:

C DEFINITIONS ::=BEGINIMPORTS Person FROM A;Employe ::= --$ implement entry -- SET

{identity Person,number INTEGER}

END

T ::= --$ implement entry nn -- OBJECT IDENTIFIER

prompt# plc409 -ln C -nty nn file.x409

Page 149: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-77

3

The compiler will understand that only the information concerning thepackage nn must be generated.

It must be noted that more than one package can be specified in thecompilation command:

In the previous example, another part could be added to the organization ofthe application, to process the Person type. The two previous parts wouldinvoke this last part in order to manipulate the Person type.

The ASN.1 description would then be cut into three packages, as shown below.

prompt# plc409 -ln C -nty 1 -nty 23 ... -nty 2 file.x409

A DEFINITIONS ::=BEGINEXPORTS Person;Person ::= --$ implement entry 1 -- SEQUENCE

{name OCTET STRING,age INTEGER}

ENDB DEFINITIONS ::=BEGINIMPORTS Person FROM A;Couple ::= --$ implement entry 2 -- SET

{man [1] Person,woman [2] Person}

ENDC DEFINITIONS ::=BEGINIMPORTS Person FROM A;Employe ::= --$ implement entry 3 -- SET

{identity Person,number INTEGER}

END

Page 150: SunLink ASN.1 Compiler User's Guide - Oracle

3-78 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Such description allows the generation of three sets of data without anyredundancies:

• The first set contains the information related to the common types (moduleA). Its processing by SunLink ASN.1 Compiler is obtained through thecommand:

• The second set contains the information concerning the types defined for themodule B without the common types. It is processed with the command:

• Finally, the third set contains the information concerning the useful types forthe module C, without the common types, and is obtained via thecommand:

3.6 DebuggingA second version of the ASN.1 library, libasn1debug.a , has been providedfor debugging purposes. It includes a trace facility for ASN.1 decoding.

To debug of an application developed using the SunLink ASN.1 Compiler,concentrate on:

• the way the routines or the structures are used by the application

• the ASN.1 description provided as input to the compiler.

Do not forget that by adapting the ASN.1 description (even taken from astandard), you may have introduced some mistakes which could causeinteroperability problems with other implementations.

prompt# plc409 -ln C -nty 1 demo.x409

prompt# plc409 -ln C -nty 2 demo.x409

prompt# plc409 -ln C -nty 3 demo.x409

Page 151: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-79

3

3.6.1 Error Detection

When processing the decoding of a given value, the compiler engine maydetect an error. In this case, it returns an error status within the global variableasn_error.

This variable is defined in the asn1_runtime.h file.

In the case where the decoder returns a failure status, the precise diagnostic ofthe failure can be found by interpreting the value of that variable.

The possible values are defined as constants, declared in the include file“asnupcon”. The interpretation of these values is provided in Table 3-8 onpage 3-79.

Table 3-8 Error Diagnostic Codes for Decoding

Name of the Constant Value Meaning

ASN_E_WGHEAD 1 wrong header encoding

ASN_E_WGFORM 2 wrong form encoding

ASN_E_WGUNDEF_L 3 wrong use of undefined length

ASN_E_WGLSUBLENG 4 wrong sublevel length. The decodedlength is greater than the given buffer.

ASN_E_WGBOOL_LENG 5 wrong boolean length (must be 1)

ASN_E_WGNULL_LENG 6 wrong null length (must be 0)

ASN_E_WGBSTR_LENG 7 wrong bit string length(must be >= 1)

ASN_E_INTERM_BSTR_PADD 8 wrong padding in constructor bitstring

ASN_E_WGSSUBSTRING 9 the length of the octet string fragmentis greater than the length of theembedding constructor octet string.

ASN_E_MISCOMPON 10 mandatory component of SET{} orSEQUENCE{} missing

ASN_E_WGCOMPON 11 unexpected component of SET{} orSEQUENCE{}

ASN_E_WGEOC 12 incorrect us of EOC

ASN_E_MISEOC 13 undefined length used but EOC missing

Page 152: SunLink ASN.1 Compiler User's Guide - Oracle

3-80 SunLink ASN.1 Compiler User’s Guide—August 1994

3

3.6.2 Switching Tracing Facility

In order to support the user during the test phase, the decoder provides afacility for tracing the decoding sessions.

To use the trace facility, link with the debug version of the library, by using—lasn1debug instead of —lasn1 . You must also add this line to your sourcefile:

ASN_E_WGLEOC_LENG 14 wrong EOC length (must be 0)

ASN_E_OVRLENGTH 15 length value too long compared toembedding length

ASN_E_OVRBOUND 16 similar to 15. may be end of bufferreached

ASN_E_MAX_IMPL 17 overflow

ASN_E_WGALLOC 18 bad memory allocation

ASN_E_WGINT_LENG 19 wrong integer length (must be >= 1)

ASN_E_WGPADD 20 wrong padding (0 <= padding <= 7)

ASN_E_EXIT 21 ASN_E_EXIT() failed

ASN_E_OVERREAL 22 overflow when decoding real

ASN_E_WGREAL_LENG 23 overflow when decoding real

asnPRECISION_LOSS 24 lose of precision when decoding real

asnWG_REAL 25 bad real decoding

ASN_E_MANTISSA_LENG 26 overflow when decoding real

ASN_E_BAD_MATRIX 27 the matrix does not correspond to thechosen access

ASN_E_CNST 28 unsatisfied constraint

ASN_E_DECREAL_NOT_IMP 29 the flag Asn_real is not definedin asn1_runtime.h however a real hasbeen detected by the decoder

#define ASN1_DEBUG

Table 3-8 Error Diagnostic Codes for Decoding (Continued)

Name of the Constant Value Meaning

Page 153: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-81

3

before including the header files generated by the ASN.1 source compilter.

To turn the trace facility on and off at runtime, use these commands:

• the function asn_trace_on() turns on the traces

• the function asn_trace_off() turns off the traces

This condition may be switched by calling special functions from the generaldecoder.

Example of the use of asn_trace_on() and asn_trace_off()• In this example, the high-level access is used. The use of the functions

asn_trace_on() and asn_trace_off() is the same when the symmetriclow-level is preferred.

3.6.2.1 Interpreting Trace Display

This example describes the way the traces displayed by the decoding tracingfacility should be interpreted.

external asn_trace_on();external asn_trace_off();

main(){..../* Tracing condition may be turned to true *//* by calling the function “asn_trace_on()” */asn_trace_on();/* this decoding will be traced */if (Dmy_routine(....)) .... else .... ;/* and reset to false by calling the *//* function “asn_trace_off()” */asn_trace_off();/* this decoding will not be traced */if (Dmy_routine(....)) .... else .... ;

}

Page 154: SunLink ASN.1 Compiler User's Guide - Oracle

3-82 SunLink ASN.1 Compiler User’s Guide—August 1994

3

Entity numberThis is a message from kernelThis message concerns ASN.1

[0099] ASN.1 --:-- start

This starts the call to the decoder

This is the ASN.1 depth level (0=top): means “input from the buffer”$ means “input from the default value”Number of octets read

[0099] ASN.1 00:00 30 [U16]+ 81 be(190)+ =”T” SEQUENCE=

Tag form:+ = constructor- = primitive

Interpretation as a tag:U = UNIVERSALA = APPLICATIONP = PRIVATEC = CONTEXTEOC = END OF CONTENTS

digits = id of tag (decimal)Octet read for the tag (hex)

Page 155: SunLink ASN.1 Compiler User's Guide - Oracle

C Language Environment 3-83

3

Figure 3-4 Traces Displayed by the Decoding Tracing Facility

[0099] ASN1 01:09 05[U5]- 00(0)- =”c” NULL=[0099] ASN1 01:11 04[U4]- 04(4)- =”d” OCTETSTRING=01020304WARNING : ASN_EXIT called with number 31 at line 10[0099] ASN1 01:17 03[U3]- 06(6)- =”e” BITSTRING=0308090a0b10[0099] ASN1 01:25 04[U4]- 03(3)- =”f” OCTETSTRING=18191a[0099] ASN1 01:30 03[U3]- 05(5)- =”g” BITSTRING=0220212223[0099] ASN1 01:37 a2[C2]+ 04(4)- =”h2” EXPLICIT TAG=[0099] ASN1 02:39 02[U2]- 02(2)- =INTEGER=0100[0099] ASN1 01:43 31[U17]+ 09(9)- =”i” SET=[0099] ASN1 02:45 df21[P33]- 01(1)- =”i1” integers

Form of length- = short+ = long

Length value (decimal) or (U)for indefinite

Octet read for the length

[0099] ASN.1 01:03 02[U2]- 01 (1) - =”a” INTERGER=1

Contents octets only for:-primitive elements-ANY with defined length-SEQUENCE OF- SET OFmay sometimes bedisplayed at next line

Semantics of element

Name of element

[0099] ASN.1 01:06 01[U1]- 01 (1) - =”b” BOOLEAN=00

Page 156: SunLink ASN.1 Compiler User's Guide - Oracle

3-84 SunLink ASN.1 Compiler User’s Guide—August 1994

3

[0099] ASN1 02:49 df20[P32]- 02(2)- =”i1b” INTEGER=0179[0099] ASN1 02$00 45[A5]- 01(1)- =”i3” INTEGER=03[0099] ASN1 01:54 30[U16]+ 06(6)- =”j” SEQUENCEOF=010100010101[0099] ASN1 01:62 31[U17]+ 03(3)- =”k” SETOF=010100[0099] ASN1 01:67 30[U16]+ 09(9)- =”l” SEQUENCEOF=010100010101010101[0099] ASN1 01:78 31[U17]+ 03(3)- =”m” SETOF=010100[0099] ASN1 01:83 30[U16]+ =”n” ANY 80(U)ANY is of indefinite length ; keep on decoding (see next lines) inorder to skip[0099] ASN1 03:85 02[U2]- 01(1)- >>...Indicates skip of contents[0099] ASN1 03:88 00[EOC] 00(0)- <<30800201ff0000Go backwards (<<) then cut value for ANY[0099] ASN1 01:90 30[U16]+ 0b(11)- =”o” SEQUENCE=[0099] ASN1 02:92 df8101[P129]- /..Begin software trap (here for default value)[0099] ASN1 02$00 7f32[A50]+ 02(2)- =”o1” EXPLICIT TAG=[0099] ASN1 03$03 30[U16]+ 00(0)- =SEQUENCE=[0099] ASN1 04$00 80[C0]- 01(1)- =”o11” INTEGER=03[0099] ASN1 02:95 ../ 02(2)- =”o2” INTEGER=0400End software trap[0099] ASN1 02:98 1f64[U100]- 02(2)- =”o3” INTEGER=8300[0099] ASN1 01:103 01[U1]- =”p” ANY 01(1)- >>... <<010100[0099] ASN1 01:106 06[U6]- 03(3)- =”q” OBJECTIDENT=050101[0099] ASN1 01:111 24[U4]+ =”r” ANY 13(19)- >>...<<241304030102032407...[0099] ASN1 01:132 23[U3]+ =”s” ANY 80(U)[0099] ASN1 03:134 03[U3]- 03(3)- >>...[0099] ASN1 03:139 23[U3]+ 80(U)[0099] ASN1 04:141 03[U3]- 02(2)- >>...[0099] ASN1 04:145 03[U3]- 02(2)- >>...[0099] ASN1 04:149 00[EOC] 00(0)-[0099] ASN1 03:151 00[EOC] 00(0)- <<238003030001022380...[0099] ASN1 01:153 30[U16]+ =”t” ANY 80(U)[0099] ASN1 03:155 01[U1]- 01(1)- >>...[0099] ASN1 03:158 01[U1]- 01(1)- >>...[0099] ASN1 03:161 00[EOC] 00(0)- <<308001010001010100...[0099] ASN1 01:163 a0[C0]+ 1a(26)- =”u” EXPLICIT TAG=[0099] ASN1 02:165 04[U4]- = ANY >>... <<041801010101010101...[0099] ASN1 01:191 30[U16]+ 00(0)- =”v” SEQUENCE=[0099] ASN1 02$00 80[C0]- 02(2)- =”v1” OCTETSTRING=0102[0099] ASN1 02$00 81[C1]- 02(2)- =”v2” OCTETSTRING=0102[0099] ASN1 --:193 end ; no error

Successful end ;otherwise error mnemonicEnd of processingTotal number of read octets

Page 157: SunLink ASN.1 Compiler User's Guide - Oracle

4-1

Using the SunLink ASN.1 Compiler 4

This chapter describes the components of the SunLink ASN.1 Compiler andprogramming environment. It provides an overview of the structure of thecompiler modules, explains the ASN.1 file naming conventions, explains howto launch the main monitor that calls each of these components, and describeshow to launch the individual modules independently. The final section in thischapter gives some information about the sample programs that are deliveredon the CD-ROM.

4.1 Compiler ModulesThe SunLink ASN.1 Compiler consists of a number of modules that execute thedifferent steps in the compilation process. The main monitor controls andlaunches each in turn. You can also launch individual modules independently.Refer to Section 1.3, “Architecture and Functions,” on page 1-5 for adescription of how the modules work together.

ASN.1 Main Monitor(plc409)

The Main Monitor schedules the successive execution of the other modules in apredetermined order.

ASN.1 Macro Preprocessor(pr409)

The macro preprocessor performs lexical and syntaxical analysis on the ASN.1source. Lexical analysis checks the accuracy of the characters used; syntacticanalysis checks the accuracy of the grammatical rules.

Page 158: SunLink ASN.1 Compiler User's Guide - Oracle

4-2 SunLink ASN.1 Compiler User’s Guide—August 1994

4

ASN.1 Analyzer(an409)

TThe ASN.1 analyzer processes input text to produce the Intermediate Formfile (.if ). It checks the input text for inconsistencies and errors, and analysesthe special comments annotating the type definitions that are supported by thecompiler.

Several .if files may be archived together in order to form an IntermediateForm Library (IFL). This is done with the help of the complementary tool(lib409 )

Linker (lk409 )The linker is used to merge several Intermediate Forms (.if files) produced bythe analyzer (or archived in a library) in order to resolve all the pendingreferences between ASN.1 modules.

At the end of the link phase, the user is warned of the occurrence of anyunresolved references. Where an unresolved reference exists, the intermediateform is not retained but may be resubmitted following another invocation ofthe linker.

C Generator (gn409c )The C generator generates C definitions from the ASN.1 input text. Thesedefinitions are used to encode and decode of values for the corresponding datatypes.

Archive Manager lib409

The archive manager handles the storage of Intermediate Forms in a library.

Note – This component is not invoked by the main monitor. You must invokeit independently.

4.2 File Naming ConventionsASN.1 source files must include the suffix .x409 . The filename and suffix arecase sensitive. For example an input file named file.X409 is rejected by thecompiler.

Page 159: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-3

4

The modules generate output files using the root file name and appending thefollowing standard suffixes:

4.3 Launching the Main MonitorThe main monitor (plc409 ) schedules the successive execution of the othermodules in a predetermined order. Launch it using a command of the generalform:

4.3.1 Source Files

The main monitor accepts two types of arguments as source_file:

ASN.1 Source FilesAll arguments that end with .x409 are interpreted as the names of text filescontaining ASN.1 source descriptions. The files are compiled, and then theassociated Intermediate Forms are generated. The name of each IntermediateForm is deduced from the source name; the suffix .x409 is replaced by .if .When more than one input source file is provided, the generation into Cproduces a single set of generated information.

Table 4-1 Suffixes of Generated Files for C Language

File Suffixes File Definitions

.if

.x409.l_prototype.h_type_ids.h_types.h_enc_matrix.h_dec_matrix.h_fill_matrix.h_encode.c_decode.c

Intermediate form fileListing of ASN.1 source, with error messagesPrototype of the generated functionsReferences to C structuresGenerated C structuresEncoding matrixDecoding matrix and associated dataFunctions used to complete the encoding matrixEncoding routine declarationsDecosing routine declarations

prompt% plc409 -ln C [options] source_file

Page 160: SunLink ASN.1 Compiler User's Guide - Oracle

4-4 SunLink ASN.1 Compiler User’s Guide—August 1994

4

The Intermediate Form files are normally deleted once the correspondinggeneration into C has been completed. They are only preserved when-ln C isnot specified, or when more than one input ASN.1 source file is provided whenthe compiler is launched.

Intermediate Form FilesAll argument names that end with .if are interpreted as the names of datafiles containing the Intermediate Forms. These, together with the results of anycompilation, are linked to generate a single Intermediate Form file that isfinally translated to C files.

4.3.2 Compile-time Options

The following compile-time options can be specified as part of the commandused to invoke the compiler.Most options are enabled by default, and can bedisabled as shown. Some options enable (or activate) other related options,even when the related option has been disabled manually.

xm (Expand ASN.1 Macros)-xm Default action. Processes macros in each ASN.1 source file provided

as argument to the command line.

--xm Does not run macros Preprocessor, bypassing the macro expansion;saves compilation time when input ASN.1 source file does notcontain any macros.

an (Syntax Analyzer)-an Default action. Analyses and compiles each ASN.1 source file

provided as an argument in the command line. Such analysis isperformed once macro expansion has been processed or bypassed.

--an Activates —xm option. Stops analysis after macro preprocessing oneach ASN.1 source file provided as argument in the command line;places the result in corresponding .m409 file.

ln (Target Language)-ln l Activates —an option. Generates outputs for target language l.

Allowed values for l are: o, O, c or C for C language

Page 161: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-5

4

--ln Default Action. Does not process generation; all producedintermediate forms are linked into a unique .if file whosebasename is taken from the file passed as first argument in thecommand line.

ac (Perform Actions)-ac Default action. Runs the different phases of compilation.

--ac Activates —la option. Does not run any compilation phase; just liststhose which would normally be executed.

la (list of actions)-la Lists calling sentences of all the different compilation phases, even if

they are not run.

--la Default action. Does not list calling sentences of different phases.

tp (Preserves Temporary Files)-tp Activates -la option. Saves used temporary files instead of deleting

them after use.

--tp Default action. Does not preserve temporary files.

fbd (forward/backward exploration)-fbd Default action. Analyzes each ASN.1 source file without imposing

any constraints on the order of declaration inside a module.

--fbd Explores each ASN.1 source file as specified by the —fwd option.

fwd (forward exploration)This option is meaningless if the fbd option is already selected.

-fwd Default action. Explores each ASN.1 source file in normal order, i.e.looking for ASN.1 items to be defined after all references pointing tothem.

--fwd

Explores each ASN.1 source file in reverse order, i.e. looking for ASN.1items to be defined before any reference pointing to it.

Page 162: SunLink ASN.1 Compiler User's Guide - Oracle

4-6 SunLink ASN.1 Compiler User’s Guide—August 1994

4

nty (Generate Entries)-nty x

Activates the generation of the packages formed by the types preceded bythe formal comment --$ implement entry x -- and the ASN.1 definitions usedby these. x must be comprised between 1 and 49. The ASN.1 definitionsincluded in other packages are ignored. This option cannot be de-selected.

4.4 Using the Macro PreprocessorIt is possible to invoke and run the Macro Preprocessor (pr409) without thehelp of the Main Monitor (plc409).

The invocation syntax is the following:

pr409 [options] infile outfile

infile is the name of the input file containing an ASN.1 description (with somemacros or not). This name must be suffixed by .x409. By default, it is thestandard input.

The resulting macro-free file is placed in an output file, outfile, which alsocontains an ASN.1 description in which all macros have been replaced by theresult of their expansion. This name must be suffixed by .x409. By default, it isthe standard output. When pr409 is invoked through the plc409 Monitor, outfileis a temporary file and will be deleted.

This unique option associated with the pr409 Preprocessor is the following one:

nc (Comment)-nc /default/

Adds the original macros text, declarations and uses, in comment.

--nc

Deletes the original macro text and declarations and uses (except where anerror occurred).

Page 163: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-7

4

4.5 Using the ASN.1 AnalyzerTo invoke and run the ASN.1 Analyzer (an409) without the help of the MainMonitor, use the following command syntax:

an409 file [options]

file is the name of the input file containing an ASN.1 macro-free description.This name must be suffixed by .x409

The resulting Intermediate Form is placed in a corresponding .if file (whosebasename is the same as the file name). Options associated with the an409analyzer are listed below:

sem (Semantics Verification)-sem /default/

Checks semantic consistency of the input x409 description.

--sem

Stops after syntax checking. Will not generate Intermediate Form files(suffixed .if)

ck (Check Only)

-ck

Does not produce Intermediate Form; just checks syntax and semanticconsistency.

--ck /default/

If semantic check has been successfully performed, then producesIntermediate Form corresponding to the ASN.1 input description.

bf (Brief)-bf

Lists neither error nor warning messages on the screen. This option has noinfluence on the compilation listing.

--bf /default/

Page 164: SunLink ASN.1 Compiler User's Guide - Oracle

4-8 SunLink ASN.1 Compiler User’s Guide—August 1994

4

Lists all compilation messages (errors or warnings) on the screen in additionto the compilation listing, if there is one.

sc (source listing)-sc /default/

Produces a compilation listing, with possible error or warning messages.This listing file is placed a in corresponding .x409.l file (that has the samebasename as the ASN.1 source file).

--sc

Does not produce a listing

tn (tables name)-tn dir /default/for PLC409

Defines a new path for compiler message table search; dir must be the nameof the directory where such table is put. dir is suffixed by the commonbasename of all these tables. By default, the compiler uses the compilermessage table file /opt/SUNWconn/asn1/bin/x409.mess . To use the file/usr/local/x409.mess , you need to use the option-tn /usr/local/x409. You can also perform the same function bysetting the shell environment variable plc409. For example:

--tn

The tn option cannot be de-selected.

nam (Rename Intermediate Form)This option can only be specified during a direct invocation of an409, and notwhen invoking plc409 monitor.

-nam N.x409

Resulting Intermediate Form file is placed in an output file whose name is thespecified basename N suffixed by .if.

prompt% setenv plc409 /usr/local/x409

Page 165: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-9

4

--nam /default when using an409/

Resulting Intermediate Form file is placed in the current file whose name isthe current basename suffixed by .if.

4.6 Using the LinkerTo invoke and run the Linker (lk409) without the help of the Main Monitor, usethe following call syntax:

lk409 [options] file [ file | -lib file ]

file arguments are the names of files containing Intermediate Forms producedby the an409 analyzer for ASN.1 descriptions. The names must be suffixed by.if. The resulting Intermediate Form is placed, by default, within the first fileargument. Options associated with the lk409 Linker may be chosen from thedifferent options listed below, except for the -lib option (this option may onlyprecede one of the file argument names which is not given in the first position):

if (Intermediate form)-if S

Produces output in Intermediate Form within the file named S.if instead ofthe name of the first file argument.

--if /default/

Produces output in Intermediate Form within first file argument.

iif (Incomplete Intermediate Form)-iif

Allows output Intermediate Form to have remaining unresolved referencesin it. This Intermediate Form may only be handled by another run of lk409.

--iif /default/

Does not allow output Intermediate Form to have remaining unresolvedreferences in it. Output Intermediate Form is not produced if it contradictsthis point, and a message is issued.

Page 166: SunLink ASN.1 Compiler User's Guide - Oracle

4-10 SunLink ASN.1 Compiler User’s Guide—August 1994

4

lib (library)-lib file

Argument file is treated as a library of x409 type definitions (instead of anindivisible x409 specification). In fact, such a file must have been createdwith the help of the lib409 tool command whose purpose is to assembleseveral Intermediate Forms resulting from plc409. This library file namemust be also suffixed by .if.

--lib

This option cannot be deselected.

4.7 Using the C GeneratorAlthough not recommended, it is possible to invoke and run the C Generator(gn409c) without the help of the Main Monitor. The call syntax is thefollowing:

gn409c [options] file

file is the name of the input file containing an Intermediate Form file with nounresolved external references. The name must be suffixed by .if.

By default, gn409c generates several files needed for the user applicationdesign and for the coding and decoding motors. Most of these files have to beincluded in the user application. In addition, two C source files are optionallygenerated in case of automatic primitive generation (by using the "--$implement entry --" notation).

Different names are assigned to the C generated files where in each case nameis the basename of the file given as the argument:

name_types.h

Include file for types definitions; tyd describes the type definitions.

name_enc_matrix.h

Include file for static coding matrix declaration and initialization; csm means“coding static matrix”.

name_dec_matrix.h

Page 167: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-11

4

Include file for static decoding matrix declaration and initialization; dsmmeans decoding static matrix.

name_fill_matrix.h

Static decoder matrix filling procedure (to be used if we are dynamicallyinitializing the encoding/decoding matrices in the symmetric low-levelaccess).; dsc means decoding static completion.

name_type_ids.h

Include file for macros definition of reference name; ref means reference.

name_prototype.h

Documentation listing of generated reference name (in the case of automaticprimitive generation, correct function headers are added at the end of thisfile). This file may be used for the prototype declarations if the Cprogramming environment supports prototyping.

name_encode.c

Source file for generated encoding primitives in case of automatic primitivegeneration (optional)

name_decode.c

Source file for generated decoding primitives in case of automatic primitivegeneration (optional)

Options associated with the gn409c Generator may be chosen from the differentoptions listed below (which may also be specified when calling plc409):

gd (generation of decoding matrix)-gd /default/

Static decoding matrix is declared and initialized in the file suffixed by_dec_matrix.h

--gd

No _dec_matrix.h file will be produced.

Page 168: SunLink ASN.1 Compiler User's Guide - Oracle

4-12 SunLink ASN.1 Compiler User’s Guide—August 1994

4

gf (generation of initialization procedure)-gf /default/

Static decoding matrix file procedure is generated which is suffixed by_fill_matrix.h.

--gf

No _fill_matrix.h file will be produced (generation of encoding matrix).

gc (generation of encoding matrix)-gc /default/

Static coding static matrix is declared and initialized in the file suffixedby _enc_matrix.h.

--gc

No _enc_matrix.h file will be produced.

gr (Generate Reference Names)-gr /default/

Produces an include file suffixed by _prototype.h which contains theprototypes of generated encoding and decoding primitives. This file is usedwhen High Level Access to PLC409 Runtime is wanted.

Also produces an include file suffixed by _type_ids.h which contains thedefinitions of macros for indexes within the generated matrices. This file isused when Low Level Access to PLC409 Runtime is wanted.

--gr

Even when the ASN.1 input text does contain the --$ implement entry --instrumentation, none of the include files described above are generated.

gp (Generation of Primitives)-gp /default/

Automatic coding and decoding primitives are generated in the file suffixedby _encode.c for the encoder and by _decode.c for the decoder. Associatedfunction headers are documented in the file suffixed by _prototype.h.

Page 169: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-13

4

--gp

Neither _encode.c nor _decode.c files are produced.

sll (Symmetrical Low Level Access)-sll /default/

Structures are generated in order to meet the requirements of the symmetriclow-level access to the PLC409 Runtime.

nty (Generate Entries)-nty x

Activates the generation of the packages formed by all the types precededby the formal comment --$ implement entry x -- and the ASN.1 definitionsused by these. x must be between 1 and 49. The ASN.1 definitions includedin other packages are ignored.

--nty

Not available; the nty option cannot be de-selected by the user.

4.8 Using the Archive ManagerThe syntax of the command line used to invoke lib409 is the following:

lib409 key file [ if_file ... ]

file argument is the name of the library file. This file may not exist if the -aoption is used, otherwise, it must correspond to a file already created by aprevious lib409 -a file ... command. This name must be suffixed by .if.

if_file arguments are the name of some Intermediate Form files generated byan409 or lk409. Consequently, these file names must be suffixed by .if.

keys associated with the lib409 Library Generator are listed on the next page.

Page 170: SunLink ASN.1 Compiler User's Guide - Oracle

4-14 SunLink ASN.1 Compiler User’s Guide—August 1994

4

a (Append)-a

Appends each given Intermediate Form File provided as if_file to the filelibrary which is created if necessary. All the Intermediate Form Files areprocessed according to their order in the arguments list and the result isstored in the file library. The file library may initially be empty.

It is possible to append the same Intermediate Form File several times to thesame library. In such a case, append is performed and consequently, theprevious version of if_file, already contained in the library file provided asfile, is not replaced.

ASN.1 modules defined in the appended Intermediate Form may alreadybelong to the current library. In such a case, the lk409 Linker takes intoaccount the order of the insertion in the current library, and has in view onlythe first one.

t (table)-t

Prints a table of contents of the given file archive file on the standardoutput, (with all the Intermediate Form range and their correspondingmodule names included).

No if_file argument is required for this key.

Note – In any case, this additional tool is called by the PLC409 Monitor. It isleft to the user to assume the design of a specific library, if necessary.

4.9 Sample ProgramsThese are located in the /opt/SUNWconn/asn1/demo directory, as follows:

4.9.0.1 demoH

Directory containing the example of the use of the high-level access to PLC409Runtime.

demo.x409

Page 171: SunLink ASN.1 Compiler User's Guide - Oracle

Using the SunLink ASN.1 Compiler 4-15

4

ASN1 description

appli.c

user application

makefile

script for the UNIX make command used to compile the example

In order to run the example:

• invoke the makefile:

make

The makefile invokes the PLC409 compiler, then compiles the source files ofthe demo and the PLC409 Runtime.

• run the resulting application:

appli

4.9.0.2 demoL

Example of the symmetric low-level access to PLC409 Runtime.

demo.x409

ASN.1 description

appli.c

user application

makefile

script for the UNIX make command used to compile the example

In order to run the example:

• invoke the makefile:

make

Page 172: SunLink ASN.1 Compiler User's Guide - Oracle

4-16 SunLink ASN.1 Compiler User’s Guide—August 1994

4

• The makefile invokes the PLC409 compiler, then complies the source files ofthe demo and the PLC409 Runtime.

• run the resulting application:

appli

Page 173: SunLink ASN.1 Compiler User's Guide - Oracle

Index-1

Index

AAbstract Syntax Notation, 1-1an409, 4-2analyzer, 1-5ANY, 2-3Application Layer, 1-1ASCII characters, 2-17, 2-21ASN.1 macro definitions, 1-7ASN.1, 1-1, 1-2, 1-3, 1-7, 1-8, 1-10, 1-11, 4-2asn_allocmem 3-59ASN_BUF_ADD_SPACE 3-5ASN_BUF_APPEND 3-7ASN_BUF_CREATE 3-9ASN_BUF_LENGTH 3-11ASN_BUF_NEW 3-12ASN_BUF_READ 3-13ASN_BUF_RELEASE 3-15ASN_BUF_REM_HEAD 3-16ASN_BUF_RESET 3-18ASN_BUF_SET_INDEX 3-19ASN_BUF_SPLIT 3-20ASN_BUF_WRITE 3-22Asn_buffer 3-1, 3-3asn_decode 3-60asn_decode_oid 3-65

asn_encode 3-54asn_encode_oid 3-67asn_freedata 3-24asn_freemem 3-55automatically generated routines, 1-11automatically generated structures, 1-11

BBackus Name Form, 2-6Basic Encoding Rules for ASN.1, 1-2BOOLEAN, 2-3boolean, 3-38Buffer Management Interface, 1-10

CC Generator, 1-5C language, 4-4CCITT X208, 2-21CHOICE, 3-37coding rules, 1-2CONFIRMED-SERVICE, 2-7

Ddata types, 1-3defined_Type, 2-13

Page 174: SunLink ASN.1 Compiler User's Guide - Oracle

Index-2 SunLink ASN.1 Compiler User’s Guide—August 1994

defined_Value, 2-13directory services, 1-1documentation files, 1-9

Eencoding and decoding algorithms, 1-3, 1-

5encoding/decoding routines interface, 1-3error or warning messages, 1-7error recovery mechanism, 1-7Exit, 2-27exporting, 2-10EXPORTS, 2-11, 2-13EXTERNAL, 2-3

FFile Transfer protocols, 1-1FTAM, 1-1

GGN409c, 1-5gn409c, 4-2

Iif files, 1-8, 4-2IFL, 1-8, 4-2implement entry, 2-29, 3-25, 3-33, 3-46implement size, 3-31, 3-32, 3-49Implementation size, 2-26IMPORTS, 2-11, 2-12, 2-14INTEGER, 2-3Interface routines, 1-10Intermediate Form File, 1-8Intermediate Form Library, 1-8, 4-2ISO 8824, 1-2ISO 8824, clauses 5.4 and 8.1.2 through

8.1.5, 2-1ISO 8825, 1-2, 1-3

LLexical , 1-7lexical item, 2-21Lexical, 1-8lexical, 1-3, 1-5LIB409, 1-8, 4-2lib409, 4-2Linker, 1-5, 1-8lk409, 4-2

Mmachine-independent representation, 1-3macro definitions, 1-7macro designed for semantics, 2-7macro notation, 2-20macro, 2-6, 2-7Main Monitor, 1-5Memory Management routines, 1-5Message Handling System, 1-1MHS, 1-1Module_Reference, 2-9, 2-14Module_References, 2-10

OOBJECT IDENTIFIER, 2-3Object_Identifier_Value, 2-9, 2-10OSI Model, 1-1OSI reference model, 1-2

PPermissive elements, 2-30plc409, 4-1PR409, 1-5pr409, 4-1Preprocessor 1-7Preprocessor, 1-5, 1-7Presentation Layer, 1-1primitive, 1-10, 3-27programming environment, 1-5

Page 175: SunLink ASN.1 Compiler User's Guide - Oracle

Index-3

Protocol Data Units, 2-1, 2-3

RREAL, 2-3reference listing, 1-9Remote Operations, 1-1ROSE, 1-1

Ssemantical, 1-3, 1-5SEQUENCE, 2-4SET, 2-4Structure declaration, 1-9structure identifiers, 3-50syntactical, 1-3, 1-5, 1-7, 1-8syntax, 1-7

Ttype (buffer), 1-10Type_Reference, 2-16TypeReferences, 2-12Types and constants translation, 1-10

Uunresolved references, 1-9, 4-2

VValueReferences, 2-12

XX500, 1-1XX

1984 and 1988 ASN.1 syntaxes, 2-91984 syntax for exporting, 2-111988 syntax for importing, 2-11

Page 176: SunLink ASN.1 Compiler User's Guide - Oracle

Index-4 SunLink ASN.1 Compiler User’s Guide—August 1994