aboutsummaryrefslogtreecommitdiff
path: root/scripts/build-attributes
blob: 1625f850bfaf7bfa29a19074610529f24adf68f5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
#!/usr/bin/env python

"""
Generate a C header file based on a YAML description of PKCS #11
attributes.  See comments in attributes.yaml for details.
"""

# Author: Rob Austein
# Copyright (c) 2015, SUNET
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This requires a third-party YAML parser.  On Debian-family Linux,
# you can install this with:
#
#   sudo apt-get install python-yaml

import os
import sys
import yaml
import argparse


def define_flags(flag_names):
  """
  Flag definitions.  Called later, here at front of program just to
  make them easier to find.
  """

  flag_names.create("DEFAULT_VALUE", "Value field contains default")
  flag_names.footnote( 1, "REQUIRED_BY_CREATEOBJECT")
  flag_names.footnote( 2, "FORBIDDEN_BY_CREATEOBJECT")
  flag_names.footnote( 3, "REQUIRED_BY_GENERATE")
  flag_names.footnote( 4, "FORBIDDEN_BY_GENERATE")
  flag_names.footnote( 5, "REQUIRED_BY_UNWRAP")
  flag_names.footnote( 6, "FORBIDDEN_BY_UNWRAP")
  flag_names.footnote( 7, "SENSITIVE")
  flag_names.footnote( 8, "PERHAPS_MODIFIABLE")
  flag_names.footnote( 9, "DEFAULT_IS_TOKEN_SPECIFIC")
  flag_names.footnote(10, "ONLY_SO_USER_CAN_SET")
  flag_names.footnote(11, "LATCHES_WHEN_TRUE")
  flag_names.footnote(12, "LATCHES_WHEN_FALSE")


class PKCS11ParseError(Exception):
  "Failure parsing PCKS #11 object definitions from YAML data."


def write_lines(*lines, **d):
  """
  Utility to simplify writing formatted text to the output stream.
  """

  for line in lines:
    args.output_file.write((line % d) + "\n")


class Flags(object):
  """
  Descriptor flag database.

  Many of these are derived from PKCS #11 Table 15  footnotes
  """

  prefix = "P11_DESCRIPTOR_"            # Prefix string for all descriptor flags

  def __init__(self):
    self.names = []
    self.notes = {}
    self.width = 0

  def create(self, name, comment = None):
    """
    Create a descriptor flag.
    """

    assert len(self.names) < 32
    name = self.prefix + name
    self.names.append((name, comment))
    if len(name) > self.width:
      self.width = len(name)

  def footnote(self, number, name):
    """
    Create a descriptor flag for a PKCS #11 table 15 footnote.
    """

    assert number not in self.notes
    self.create(name, "Section 10.2 table 15 footnote #%2d" % number)
    self.notes[number] = self.prefix + name

  def write(self):
    """
    Generate the flags, assigning bit positions as we go.
    """

    assert len(self.names) < 32
    self.width = (((self.width + 4) >> 2) << 2) - 1
    bit = 1
    for name, comment in self.names:
      format = "#define %(name)s 0x%(bit)08x"
      if comment is not None:
        format += "  /* %(comment)s */"
      write_lines(format, bit = bit, comment = comment, name = "%-*s" % (self.width, name))
      bit <<= 1


class AttributeNumbers(dict):
  """
  Attribute names and numbers scraped (yuck) from pkcs11t.h.
  """

  def __init__(self, filename):
    with open(filename, "r") as f:
      for line in f:
        word = line.split()
        if len(word) <= 2 or word[0] != "#define" or not word[1].startswith("CKA_"):
          continue
        if word[2] in self:
          continue
        if word[2].startswith("(CKF_ARRAY_ATTRIBUTE|"):
          word[2] = word[2].translate(None, "()").split("|")[1]
        self[word[1]] = int(word[2], 16)


class Attribute(object):
  """
  Definition of one attribute.
  """

  def __init__(self, name, type = None, footnotes = None, default = None, value = None, unimplemented = False):
    assert value is None or default is None
    self.name = name
    self.type = type
    self.footnotes = footnotes
    self.default = self.convert_integers(default)
    self.value   = self.convert_integers(value)
    self.unimplemented = unimplemented

  @staticmethod
  def convert_integers(val):
    """
    Convert a non-negative integer initialization value into a byte array.
    """

    if not isinstance(val, (int, long)):
      return val
    if val < 0:
      raise ValueError("Negative integers not legal here: %s" % val)
    bytes = []
    while val > 0:
      bytes.insert(0, val & 0xFF)
      val >>= 8
    return bytes or [0]

  def inherit(self, other):
    """
    Merge values from paraent attribute definition, if any.
    """

    for k in ("type", "footnotes", "default", "value"):
      if getattr(self, k) is None:
        setattr(self, k, getattr(other, k))
    self.unimplemented = self.unimplemented or other.unimplemented

  def format_flags(self):
    """
    Generate the descriptor flags field.
    """

    flags = []
    if self.footnotes:
      flags.extend(flag_names.notes[f] for f in self.footnotes)
    if self.value is None and self.default is not None:
      flags.append("P11_DESCRIPTOR_DEFAULT_VALUE")
    flags = " | ".join(flags)
    return flags or "0"

  def format_size(self):
    """
    Generate the descriptor size field.
    """

    if isinstance(self.type, str) and self.type.startswith("CK_"):
      return "sizeof(%s)" % self.type
    elif self.type in ("rfc2279string", "biginteger", "bytearray"):
      return "0"
    else:
      raise PKCS11ParseError("Unknown meta-type %r" % self.type)

  def format_length(self):
    """
    Generate the descriptor length field.
    """

    value = self.value or self.default
    if isinstance(value, list):
      return "sizeof(const_0x%s)" % "".join("%02x" % v for v in value)
    elif value and isinstance(self.type, str) and self.type.startswith("CK_"):
      return "sizeof(%s)" % self.type
    else:
      return "0"

  def format_value(self):
    """
    Generate the descriptor value field.
    """

    value = self.value or self.default
    if not value:
      return "NULL_PTR"
    elif isinstance(value, list):
      return "const_0x" + "".join("%02x" % v for v in value)
    else:
      return "&const_" + value

  def format_constant(self, constants):
    """
    Generate constant initializer values.  These are merged so that we
    only end up declaring one copy of each initializer value no matter
    how many attributes use it.
    """

    value = self.value or self.default
    if not self.unimplemented and value:
      if isinstance(value, list):
        constants.add("static const CK_BYTE const_%s[] = { %s };" % (
          "0x" + "".join("%02x" % v for v in value),
          ", ".join("0x%02x" % v for v in value)))
      else:
        constants.add("static const %s const_%s = %s;" % (self.type, value, value))

  def generate(self):
    """
    Generate the descriptor line for this attribute.
    """

    if not self.unimplemented:
      args.output_file.write("  { %s, %s, %s, %s, %s },\n" % (
        self.name, self.format_size(), self.format_length(), self.format_value(), self.format_flags()))


class Class(object):
  """
  A PKCS #11 class.
  """

  def __init__(self, db, name, superclass = None, concrete = False, **attrs):
    assert all(a.startswith("CKA_") for a in attrs), "Non-attribute: %r" % [a for a in attrs if not a.startswith("CKA_")]
    self.attributes = dict((k, Attribute(k, **v)) for k, v in attrs.iteritems())
    self.db = db
    self.name = name
    self.superclass = superclass
    self.concrete = concrete

  def inherit(self, other):
    """
    Inherit attributes from parent type.
    """

    for k, v in other.attributes.iteritems():
      if k not in self.attributes:
        self.attributes[k] = v
      else:
        self.attributes[k].inherit(v)

  def collect_constants(self, constants):
    """
    Collect initialization constants for all attributes.
    """

    if self.concrete:
      for a in self.attributes.itervalues():
        a.format_constant(constants)

  def generate(self):
    """
    Generate a descriptor for this type.
    """

    if self.concrete:

      write_lines("",
                  "static const p11_attribute_descriptor_t p11_attribute_descriptor_%(name)s[] = {",
                  name = self.name)

      for a in sorted(self.attributes, key = lambda x: attribute_numbers[x]):
        self.attributes[a].generate()

      write_lines("};",
                  "",
                  "static const p11_descriptor_t p11_descriptor_%(name)s = {",
                  "  p11_attribute_descriptor_%(name)s,",
                  "  sizeof(p11_attribute_descriptor_%(name)s)/sizeof(p11_attribute_descriptor_t)",
                  "};",
                  name = self.name)

  def keyclassmap(self):
    """
    Generate a keyclass map entry if this is a concrete key type.
    """

    if self.concrete and all(k in self.attributes and self.attributes[k].value for k in ("CKA_CLASS", "CKA_KEY_TYPE")):
      write_lines(" { %s, %s, &p11_descriptor_%s }," % (
        self.attributes["CKA_CLASS"].value, self.attributes["CKA_KEY_TYPE"].value, self.name))


class DB(object):
  """
  Object type database parsed from YAML
  """

  def __init__(self, y):
    self.ordered = [Class(self, **y) for y in y]
    self.named = dict((c.name, c) for c in self.ordered)
    for c in self.ordered:
      if c.superclass is not None:
        c.inherit(self.named[c.superclass])

  def generate(self):
    """
    Generate output for everything in the database.
    """

    constants = set()
    for c in self.ordered:
      c.collect_constants(constants)
    for constant in sorted(constants):
      write_lines(constant)
    for c in self.ordered:
      c.generate()
    write_lines("",
                "static const p11_descriptor_keyclass_map_t p11_descriptor_keyclass_map[] = {")
    for c in self.ordered:
      c.keyclassmap()
    write_lines("};")

# Main program

parser = argparse.ArgumentParser(description = __doc__, formatter_class = argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--pkcs11t-file", help = "Alternate location for pkcs11t.h",                            default = "pkcs11t.h")
parser.add_argument("yaml_file",      help = "Input YAML file", nargs = "?", type = argparse.FileType("r"), default = sys.stdin)
parser.add_argument("output_file",    help = "Output .h file",  nargs = "?", type = argparse.FileType("w"), default = sys.stdout)
args = parser.parse_args()

attribute_numbers = AttributeNumbers(args.pkcs11t_file)

db = DB(yaml.load(args.yaml_file))

args.output_file.write('''\
/*
 * This file was generated automatically from %(input)s by %(script)s.  Do not edit this file directly.
 */

typedef struct {
  CK_ATTRIBUTE_TYPE type;
  CK_ULONG size;                        /* Size in bytes if this is a fixed-length attribute */
  CK_ULONG length;                      /* Length in bytes of the object to which value points */
  const void *value;                    /* Default or constant depending on P11_DESCRIPTOR_DEFAULT_VALUE */
  unsigned long flags;                  /* (NULL value with P11_DESCRIPTOR_DEFAULT_VALUE means zero length default */
} p11_attribute_descriptor_t;

typedef struct {
  const p11_attribute_descriptor_t *attributes;
  CK_ULONG n_attributes;
} p11_descriptor_t;

typedef struct {
  CK_OBJECT_CLASS object_class;
  CK_KEY_TYPE key_type;
  const p11_descriptor_t *descriptor;
} p11_descriptor_keyclass_map_t;

''' % dict(script = os.path.basename(sys.argv[0]), input  = args.yaml_file.name))

flag_names = Flags()
define_flags(flag_names)
flag_names.write()
write_lines("")
db.generate()
\ref osTimer. /// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior. /// \param[in] argument argument to the timer call back function. /// \return timer ID for reference by other functions or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS. osTimerId osTimerCreate (osTimerDef_t *timer_def, os_timer_type type, void *argument); /// Start or restart a timer. /// \param[in] timer_id timer ID obtained by \ref osTimerCreate. /// \param[in] millisec time delay value of the timer. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS. osStatus osTimerStart (osTimerId timer_id, uint32_t millisec); /// Stop the timer. /// \param[in] timer_id timer ID obtained by \ref osTimerCreate. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS. osStatus osTimerStop (osTimerId timer_id); /// Delete a timer that was created by \ref osTimerCreate. /// \param[in] timer_id timer ID obtained by \ref osTimerCreate. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS. osStatus osTimerDelete (osTimerId timer_id); // ==== Signal Management ==== /// Set the specified Signal Flags of an active thread. /// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. /// \param[in] signals specifies the signal flags of the thread that should be set. /// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. /// \note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS. int32_t osSignalSet (osThreadId thread_id, int32_t signals); /// Clear the specified Signal Flags of an active thread. /// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. /// \param[in] signals specifies the signal flags of the thread that shall be cleared. /// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. /// \note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS. int32_t osSignalClear (osThreadId thread_id, int32_t signals); /// Get Signal Flags status of an active thread. /// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. /// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. /// \note MUST REMAIN UNCHANGED: \b osSignalGet shall be consistent in every CMSIS-RTOS. int32_t osSignalGet (osThreadId thread_id); /// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread. /// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag. /// \param[in] millisec timeout value or 0 in case of no time-out. /// \return event flag information or error code. /// \note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS. os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); // ==== Mutex Management ==== /// Define a Mutex. /// \param name name of the mutex object. /// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osMutexDef(name) \ extern osMutexDef_t os_mutex_def_##name #else // define the object #define osMutexDef(name) \ uint32_t os_mutex_cb_##name[3]; \ osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } #endif /// Access a Mutex definition. /// \param name name of the mutex object. /// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osMutex(name) \ &os_mutex_def_##name /// Create and Initialize a Mutex object. /// \param[in] mutex_def mutex definition referenced with \ref osMutex. /// \return mutex ID for reference by other functions or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS. osMutexId osMutexCreate (osMutexDef_t *mutex_def); /// Wait until a Mutex becomes available. /// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. /// \param[in] millisec timeout value or 0 in case of no time-out. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS. osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec); /// Release a Mutex that was obtained by \ref osMutexWait. /// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS. osStatus osMutexRelease (osMutexId mutex_id); /// Delete a Mutex that was created by \ref osMutexCreate. /// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS. osStatus osMutexDelete (osMutexId mutex_id); // ==== Semaphore Management Functions ==== #if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available /// Define a Semaphore object. /// \param name name of the semaphore object. /// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osSemaphoreDef(name) \ extern osSemaphoreDef_t os_semaphore_def_##name #else // define the object #define osSemaphoreDef(name) \ uint32_t os_semaphore_cb_##name[2]; \ osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } #endif /// Access a Semaphore definition. /// \param name name of the semaphore object. /// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osSemaphore(name) \ &os_semaphore_def_##name /// Create and Initialize a Semaphore object used for managing resources. /// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore. /// \param[in] count number of available resources. /// \return semaphore ID for reference by other functions or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS. osSemaphoreId osSemaphoreCreate (osSemaphoreDef_t *semaphore_def, int32_t count); /// Wait until a Semaphore token becomes available. /// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. /// \param[in] millisec timeout value or 0 in case of no time-out. /// \return number of available tokens, or -1 in case of incorrect parameters. /// \note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS. int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec); /// Release a Semaphore token. /// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS. osStatus osSemaphoreRelease (osSemaphoreId semaphore_id); /// Delete a Semaphore that was created by \ref osSemaphoreCreate. /// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS. osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); #endif // Semaphore available // ==== Memory Pool Management Functions ==== #if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available /// \brief Define a Memory Pool. /// \param name name of the memory pool. /// \param no maximum number of blocks (objects) in the memory pool. /// \param type data type of a single block (object). /// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osPoolDef(name, no, type) \ extern osPoolDef_t os_pool_def_##name #else // define the object #define osPoolDef(name, no, type) \ uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \ osPoolDef_t os_pool_def_##name = \ { (no), sizeof(type), (os_pool_m_##name) } #endif /// \brief Access a Memory Pool definition. /// \param name name of the memory pool /// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osPool(name) \ &os_pool_def_##name /// Create and Initialize a memory pool. /// \param[in] pool_def memory pool definition referenced with \ref osPool. /// \return memory pool ID for reference by other functions or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS. osPoolId osPoolCreate (osPoolDef_t *pool_def); /// Allocate a memory block from a memory pool. /// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. /// \return address of the allocated memory block or NULL in case of no memory available. /// \note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS. void *osPoolAlloc (osPoolId pool_id); /// Allocate a memory block from a memory pool and set memory block to zero. /// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. /// \return address of the allocated memory block or NULL in case of no memory available. /// \note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS. void *osPoolCAlloc (osPoolId pool_id); /// Return an allocated memory block back to a specific memory pool. /// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate. /// \param[in] block address of the allocated memory block that is returned to the memory pool. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS. osStatus osPoolFree (osPoolId pool_id, void *block); #endif // Memory Pool Management available // ==== Message Queue Management Functions ==== #if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available /// \brief Create a Message Queue Definition. /// \param name name of the queue. /// \param queue_sz maximum number of messages in the queue. /// \param type data type of a single message element (for debugger). /// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osMessageQDef(name, queue_sz, type) \ extern osMessageQDef_t os_messageQ_def_##name #else // define the object #define osMessageQDef(name, queue_sz, type) \ uint32_t os_messageQ_q_##name[4+(queue_sz)]; \ osMessageQDef_t os_messageQ_def_##name = \ { (queue_sz), (os_messageQ_q_##name) } #endif /// \brief Access a Message Queue Definition. /// \param name name of the queue /// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osMessageQ(name) \ &os_messageQ_def_##name /// Create and Initialize a Message Queue. /// \param[in] queue_def queue definition referenced with \ref osMessageQ. /// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. /// \return message queue ID for reference by other functions or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS. osMessageQId osMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id); /// Put a Message to a Queue. /// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. /// \param[in] info message information. /// \param[in] millisec timeout value or 0 in case of no time-out. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS. osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec); /// Get a Message or Wait for a Message from a Queue. /// \param[in] queue_id message queue ID obtained with \ref osMessageCreate. /// \param[in] millisec timeout value or 0 in case of no time-out. /// \return event information that includes status code. /// \note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS. os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); #endif // Message Queues available // ==== Mail Queue Management Functions ==== #if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available /// \brief Create a Mail Queue Definition. /// \param name name of the queue /// \param queue_sz maximum number of messages in queue /// \param type data type of a single message element /// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osMailQDef(name, queue_sz, type) \ extern osMailQDef_t os_mailQ_def_##name #else // define the object #define osMailQDef(name, queue_sz, type) \ uint32_t os_mailQ_q_##name[4+(queue_sz)]; \ uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \ void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ osMailQDef_t os_mailQ_def_##name = \ { (queue_sz), sizeof(type), (os_mailQ_p_##name) } #endif /// \brief Access a Mail Queue Definition. /// \param name name of the queue /// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osMailQ(name) \ &os_mailQ_def_##name /// Create and Initialize mail queue. /// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ /// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL. /// \return mail queue ID for reference by other functions or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS. osMailQId osMailCreate (osMailQDef_t *queue_def, osThreadId thread_id); /// Allocate a memory block from a mail. /// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. /// \param[in] millisec timeout value or 0 in case of no time-out /// \return pointer to memory block that can be filled with mail or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS. void *osMailAlloc (osMailQId queue_id, uint32_t millisec); /// Allocate a memory block from a mail and set memory block to zero. /// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. /// \param[in] millisec timeout value or 0 in case of no time-out /// \return pointer to memory block that can be filled with mail or NULL in case of error. /// \note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS. void *osMailCAlloc (osMailQId queue_id, uint32_t millisec); /// Put a mail to a queue. /// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. /// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS. osStatus osMailPut (osMailQId queue_id, void *mail); /// Get a mail from a queue. /// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. /// \param[in] millisec timeout value or 0 in case of no time-out /// \return event that contains mail information or error code. /// \note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS. os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); /// Free a memory block from a mail. /// \param[in] queue_id mail queue ID obtained with \ref osMailCreate. /// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet. /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. osStatus osMailFree (osMailQId queue_id, void *mail); #endif // Mail Queues available #ifdef __cplusplus } #endif #endif // _CMSIS_OS_H