What does htons() do on a Big-Endian system? - c

htons() converts host byte order to network byte order.
Network byte order is Big-Endian and host byte order can be either Little-Endian or Big-Endian.
On a Little Endian system htons() will convert the order of a multi-byte variable to Big-Endian. What will htons() do in case if the host byte order is also Big-Endian?

What will htons() do in case if the host byte order is also big endian?
Nothing - quite literally. The purpose of introducing htons() in the first place is to let you write code that does not care about the endianness of your system. Header file where the functions are defined is the only place where endianness comes into play.
Here is one implementation that replaces htons with parentheses around its parameter expression:
#if BYTE_ORDER == BIG_ENDIAN
#define HTONS(n) (n)
#define NTOHS(n) (n)
#define HTONL(n) (n)
#define NTOHL(n) (n)
#else
#define HTONS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define NTOHS(n) (((((unsigned short)(n) & 0xFF)) << 8) | (((unsigned short)(n) & 0xFF00) >> 8))
#define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
((((unsigned long)(n) & 0xFF00)) << 8) | \
((((unsigned long)(n) & 0xFF0000)) >> 8) | \
((((unsigned long)(n) & 0xFF000000)) >> 24))
#define NTOHL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \
((((unsigned long)(n) & 0xFF00)) << 8) | \
((((unsigned long)(n) & 0xFF0000)) >> 8) | \
((((unsigned long)(n) & 0xFF000000)) >> 24))
#endif
#define htons(n) HTONS(n)
#define ntohs(n) NTOHS(n)
#define htonl(n) HTONL(n)
#define ntohl(n) NTOHL(n)

Related

Purpose of double underscore pointer operator for C functions

I am writing some C code that is for a microcontroller and have come across a curious couple of statements in some generated drivers for a peripheral I am using. Seemingly, a function uint8_t gapm_reset_req_handler (void) is supposed to reset a handler and return a status. The function is seemingly failing in its purpose, which surprises me as it seems simple enough. The relevant code I would like to ask about is this function and that INTERFACE_UNPACK_UINT8 line.
uint8_t gapm_reset_req_handler (void) {
uint8_t u8Operation, u8Status;
INTERFACE_MSG_INIT(GAPM_RESET_CMD, TASK_GAPM);
INTERFACE_PACK_ARG_UINT8(GAPM_RESET);
INTERFACE_SEND_WAIT(GAPM_CMP_EVT, TASK_GAPM);
INTERFACE_UNPACK_UINT8(&u8Operation);
INTERFACE_UNPACK_UINT8(&u8Status);
INTERFACE_MSG_DONE();
if(u8Operation!=GAPM_RESET)
return AT_BLE_FAILURE;
return u8Status;}
These INTERFACE messages are defined in another file, and I am a bit lost at what exactly is supposed to be accomplished by the generated code regarding the use of the double underscore on the ptr variable. Does anyone have any intuition as to what is going on? To me, it looks like some operation on the value that is passed to it but the use of the double underscore confuses me as I thought that was just for macros. Any thoughts are greatly appreciated!
Specific line
#define INTERFACE_UNPACK_UINT8(ptr)\
*ptr = *__ptr++
Full Definition of INTERFACE Code:
#ifndef __INTERFACE_H__
#define __INTERFACE_H__
#include "event.h"
#define INTERFACE_HDR_LENGTH 9
#define INTERFACE_API_PKT_ID 0x05
#define INTERFACE_SEND_BUF_MAX 600
#define INTERFACE_RCV_BUFF_LEN 500
extern uint8_t interface_send_msg[INTERFACE_SEND_BUF_MAX];
void platform_send_lock_aquire(void);
void platform_send_lock_release(void);
#define INTERFACE_MSG_INIT(msg_id, dest_id) \
do{\
uint8_t* __ptr = interface_send_msg;\
uint16_t __len;\
platform_send_lock_aquire();\
*__ptr++ = (INTERFACE_API_PKT_ID);\
*__ptr++ = ((msg_id) & 0x00FF );\
*__ptr++ = (((msg_id)>>8) & 0x00FF );\
*__ptr++ = ((dest_id) & 0x00FF );\
*__ptr++ = (((dest_id)>>8) & 0x00FF );\
*__ptr++ = ((TASK_EXTERN) & 0x00FF );\
*__ptr++ = (((TASK_EXTERN)>>8) & 0x00FF );\
__ptr += 2
#define INTERFACE_PACK_ARG_UINT8(arg)\
*__ptr++ = (arg)
#define INTERFACE_PACK_ARG_UINT16(arg)\
*__ptr++ = ((arg) & 0x00FF);\
*__ptr++ = (((arg) >> 8) & 0x00FF)
#define INTERFACE_PACK_ARG_UINT32(arg) \
*__ptr++ = (uint8_t)((arg) & 0x00FF );\
*__ptr++ = (uint8_t)(( (arg) >> 8) & 0x00FF) ;\
*__ptr++ = (uint8_t)(( (arg) >> 16) & 0x00FF);\
*__ptr++ = (uint8_t)(( (arg) >> 24) & 0x00FF)
#define INTERFACE_PACK_ARG_BLOCK(ptr,len)\
memcpy(__ptr, ptr, len);\
__ptr += len
#define INTERFACE_PACK_ARG_DUMMY(len)\
__ptr += len
#define INTERFACE_PACK_LEN()\
__len = __ptr - &interface_send_msg[INTERFACE_HDR_LENGTH];\
interface_send_msg[7] = ((__len) & 0x00FF );\
interface_send_msg[8] = (((__len)>>8) & 0x00FF);\
__len += INTERFACE_HDR_LENGTH;
#define INTERFACE_SEND_NO_WAIT()\
INTERFACE_PACK_LEN();\
interface_send(interface_send_msg, __len)
#define INTERFACE_SEND_WAIT(msg, src)\
watched_event.msg_id = msg;\
watched_event.src_id = src;\
INTERFACE_PACK_LEN();\
interface_send(interface_send_msg, __len);\
if(platform_cmd_cmpl_wait()){return AT_BLE_FAILURE;}\
__ptr = watched_event.params;\
#define INTERFACE_MSG_DONE()\
platform_send_lock_release();\
}while(0)
#define INTERFACE_UNPACK_INIT(ptr)\
do{\
uint8_t* __ptr = (uint8_t*)(ptr);\
#define INTERFACE_UNPACK_UINT8(ptr)\
*ptr = *__ptr++
#define INTERFACE_UNPACK_UINT16(ptr)\
*ptr = (uint16_t)__ptr[0]\
| ((uint16_t)__ptr[1] << 8);\
__ptr += 2
#define INTERFACE_UNPACK_UINT32(ptr)\
*ptr = (uint32_t)__ptr[0] \
| ((uint32_t)__ptr[1] << 8) \
| ((uint32_t)__ptr[2] << 16)\
| ((uint32_t)__ptr[3] << 24);\
__ptr += 4
#define INTERFACE_UNPACK_BLOCK(ptr, len)\
memcpy(ptr, __ptr, len);\
__ptr += len
#define INTERFACE_UNPACK_SKIP(len)\
__ptr += (len)
#define INTERFACE_UNPACK_DONE()\
}while(0)
void interface_send(uint8_t* msg, uint16_t u16TxLen);
#endif /* HCI_H_ */
*ptr = *__ptr++ is simply a byte copy followed by increasing the source pointer by one. __ptr is a local variable declared inside one of the macros then re-used in the other macros.
Notably, it is bad practice to use identifiers starting with underscore and particularly with two underscore or one underscore + an upper case letter. These are reserved for the compiler and standard lib, and the lib you post does not appear to belong to either. So there is reason to believe it was badly designed.
The following function-like macro nightmare confirms this - this is some horrible code with non-existent type safety and massive potential for undefined behavior upon bitwise arithmetic with signed numbers. People used to write macro crap like this before function inlining became industry standard back in the 1980s-1990s. Although stdint.h was introduced in 1999 so more likely they were just incompetent.
As for what the code does, it is much simpler than it looks. There's just various macros for shoveling data from one data type to another, apparently part of some protocol encoding/decoding. They also seem to make various assumptions about endianess that aren't portable.
Please never use or trust code provided to you by some silicon vendor. They have a very long tradition of employing the absolutely worst programmers in the world. If someone wrote microcontroller code like this in a normal company, they would get fired immediately. Similarly, don't trust the average open source barf posted on Github either.

Extracting bytes from a 32 bits number

This is not important and should be quite simple, I just don't understand what I'm doing wrong.
The story behind this is that I'm playing with tinyNeoPixel lib on the attiny85, and I'm trying to dive a bit deeper than I need.
This is traditional ANSI C and I'm using a Raspberry Pi3 for this test, but for this case this should be irrelevant. The sizeof(c) on the printf just shows that 'c' is 4 bytes, as expected.
I'm trying to extract the Red, Green, and Blue part of a color that's stored as a 32 bits number
Obviously I'm failing to return the result as a 1 byte value, can same one please tell me how do I do that ? Just casting to (uint8_t) just produces zero.
Thank you.
pi3:~/src$ cat a.c
#include <stdio.h>
typedef unsigned char uint8_t;
typedef unsigned long int uint32_t;
#define Red(x) (x & 0xff000000)
#define Green(x) (x & 0x00ff0000)
#define Blue(x) (x & 0x0000ff00)
void main()
{
uint32_t c;
uint8_t r,g,b;
c=0xffeecc00;
r=Red(c);
g=Green(c);
b=Blue(c);
printf("%d - %08x - %02x %02x %02x\n", sizeof(c), c, r, g, b);
printf("%d - %08x - %02x %02x %02x\n", sizeof(c), c, Red(c), Green(c), Blue(c));
}
pi3:~/src$ gcc a.c -o a
pi3:~/src$ ./a
4 - ffeecc00 - 00 00 00
4 - ffeecc00 - ff000000 ee0000 cc00
The solution is:
#define Red(x) (((x) & 0xff000000) >> 24)
#define Green(x) (((x) & 0x00ff0000) >> 16)
#define Blue(x) (((x) & 0x0000ff00) >> 8)
With this macros this produces
pi3:~/src$ ./a
4 - ffeecc00 - ff ee cc
4 - ffeecc00 - ff ee cc
as it should.
Thank you guys.
You need to shift as well as mask. That is, try something like
#define Red(x) (((x) & 0xff000000) >> 24)
and similarly for your Green() and Blue() macros.
(Also note that I've added two extra pairs of parentheses to the macro definition, for safety in expansion.)

How to construct a C macro for low-level bit masking?

I'm beginning to learn programming embedded C micro-controllers and want to do something that would make my life easier. Usually when dealing with bit masking everybody uses stuff like:
char a = (1 << 3) | (1 << 1) | (1 << 5);
I want to use a macro for something like this. For just one mask I can simply define this macro:
#define M(n) (1 << (n))
Nothing fancy. The problem is that I cannot come with a good solution that would allow me to type:
a = MM( 3, 1, 5 ); or at least a = MM( 3, 3, 1, 5 ); (where the first 3 is the number of arguments)
instead of a = M(3) | M(1) | M(5);
I came up with a solution which implied using functions with multiple arguments but it's really bugging me that I cannot do it using a macro.
Found the answer.
#define M(a) (1 << (a))
#define M2(a, b) (M(a) | M(b))
#define M3(a, b...) (M(a) | M2(b))
#define M4(a, b...) (M(a) | M3(b))
// can be continued
#define GET_MACRO( _1, _2, _3, _4, NAME, ... ) NAME
#define MM(args...) GET_MACRO( args, M4, M3, M2, M )(args)
this uses the answer in this thread
Maybe this can help:
#define BITMASK_SET(x,y) ((x) |= (y))
#define BITMASK_CLEAR(x,y) ((x) &= (~(y)))
#define BITMASK_FLIP(x,y) ((x) ^= (y))
#define BITMASK_CHECK(x,y) ((x) & (y))
use boost
#include <boost/preprocessor/tuple/to_seq.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/control/if.hpp>
#define M(n) (1 << (n))
#define F(r, data, i, elem) BOOST_PP_IF(i, data, ) M(elem)
#define MM(...) BOOST_PP_SEQ_FOR_EACH_I(F, | , BOOST_PP_TUPLE_TO_SEQ((__VA_ARGS__)) )
...
char a = MM(3, 1, 5);//char a = (1 << (3)) | (1 << (1)) | (1 << (5)) ;

big endian swap macro "uswap" leads to unexpected error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm facing following problem.
The macro
#define uswap_32(x) \
((((x) & 0xff000000) >> 24) | \
(((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | \
(((x) & 0x000000ff) << 24))
get's following number as argument x = 0x49074808
Why does my program break/resets here??
Thx
EDIT:
Description of my real application:
I have a bootloader sitting at flash start address 0x08000000U going till 0x08004000U.
After the bootloader there is a uImage header(taken from uboot) in flash, with size 0x40.
In my application, I just want to check, if there is actually a correct uImage header, because I have two bootloader versions. One can handle images of type uImage and the other one can't. In the last case, after the bootloader application there is no uImage header at all, there is application code!
In the application I just want to check the header crc:
#define UIMAGE_FLASH_ADDRESS (0x08004000U)
image_header_t *header;
header = (image_header_t *) UIMAGE_FLASH_ADDRESS;
if (image_check_hcrc(header))
/* do something...*/
static int image_check_hcrc(const image_header_t *hdr)
{
uint32_t hcrc;
uint32_t len = image_get_header_size();
image_header_t header;
/* Copy header so we can blank CRC field for re-calculation */
memcpy(&header, (char *)hdr, image_get_header_size());
header.ih_hcrc = 0; // byte order independent
hcrc = crc32(0, (unsigned char *)&header, len);
return hcrc == image_get_hcrc(hdr);
}
The call for uswap_32() happens in the last line of above function:
#define uswap_32(x) \
((((x) & 0xff000000) >> 24) | \
(((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | \
(((x) & 0x000000ff) << 24))
# define cpu_to_be32(x) uswap_32(x)
# define be32_to_cpu(x) uswap_32(x)
#define uimage_to_cpu(x) be32_to_cpu(x)
#define cpu_to_uimage(x) cpu_to_be32(x)
#define image_get_hdr_l(f) \
static inline uint32_t image_get_##f(const image_header_t *hdr) \
{ \
return uimage_to_cpu(hdr->ih_##f); \
}
image_get_hdr_l(magic) /* image_get_magic */
image_get_hdr_l(hcrc) /* image_get_hcrc */
image_get_hdr_l(time) /* image_get_time */
image_get_hdr_l(size) /* image_get_size */
image_get_hdr_l(load) /* image_get_load */
image_get_hdr_l(ep) /* image_get_ep */
image_get_hdr_l(dcrc) /* image_get_dcrc */
#define image_get_hdr_b(f) \
static inline uint8_t image_get_##f(const image_header_t *hdr) \
{ \
return hdr->ih_##f; \
}
image_get_hdr_b(os) /* image_get_os */
image_get_hdr_b(arch) /* image_get_arch */
image_get_hdr_b(type) /* image_get_type */
image_get_hdr_b(comp) /* image_get_comp */
It is a good idea to assign x to a local variable within a macro. Otherwise, if an expression is passed as an argument to the macro, it will be evaluated 4 times. For example, uswap(2+3), or even worse, uswap(some_func(x)).
Second issue - you need to add explicit UL type modifier for the constants. Here is a safer version of the macro:
#define uswap_32(x) ({\
uint32_t _x = (x);\
(uint32_t)(\
((_x & 0xff000000UL) >> 24) | \
((_x & 0x00ff0000UL) >> 8) | \
((_x & 0x0000ff00UL) << 8) | \
((_x & 0x000000ffUL) << 24)); \
})

Multi line inline assembly macro with strings

I'm trying to implement a macro ("MY_MACRO"), which stores a string preceded by a 32 bit integer number in a certain section ("my_section").
Example: MY_MACRO(200, "my first string %u %x");
Here are the options I tried and the problems I'm facing with. I would appreciate any help.
(gcc 4.7.3. MIPS cpu)
Option A:
#define MY_MACRO(_num, _string)\
asm volatile(".pushsection .my_section");\
asm volatile(".byte %0, %1, %2, %3" : : "i"((_num >> 24) & 0xFF), "i"((_num >> 16) & 0xFF), "i"((_num >> 8) & 0xFF), "i"(_num & 0xFF)); /* Store the number */ \
asm volatile(".ascii " #_string);\
asm volatile(".popsection");
Compile error (it doesn't occur for each usage of the macro):
c:\Temp\ccpDEDnt.s: Assembler messages:
c:\Temp\ccpDEDnt.s:1024: Warning: .popsection without corresponding .pushsection; ignored
I think the reason is a compiler optimization which changes the instructions order (although each asm instruction is volatile, the compiler is allowed to change the order).
Q: Is there any way to disable the compiler optimizations just for the scope of these lines without #pragma?
This issue led me to find a solution in which the four asm instructions are unified.
Option B:
#define MY_MACRO(_num, _string)\
asm volatile(".pushsection .my_section\n\t" \
".byte %0, %1, %2, %3\n\t" \
".ascii " #_string "\n\t" \
".popsection" \
: : "i"((_num >> 24) & 0xFF), "i"((_num >> 16) & 0xFF), "i"((_num >> 8) & 0xFF), "i"(_num & 0xFF));
Compiler errors:
foo.c:733:13: error: invalid 'asm': operand number missing after %-letter
foo.c:733:13: error: invalid 'asm': operand number out of range
Since the string includes the percent sign (%), the compiler interprets it as an asm operands.
Option C:
#define MY_MACRO(_num, _string)\
asm volatile(".pushsection .my_section\n\t" \
".byte %0, %1, %2, %3\n\t" \
".ascii %4\n\t" \
".popsection" \
: : "i"((_num >> 24) & 0xFF), "i"((_num >> 16) & 0xFF), "i"((_num >> 8) & 0xFF), "i"(_num & 0xFF), "X"(#_string));
Here I tried to pass the string as an operand. I don't even know if it's feasible.
I didn't manage to compile this code.
Option B is the right way, however you will need to double all percent signs (%) occurring in your string because that's interpreted as an operand placeholder in the inline asm.
If you don't particularly care about ordering or inlining, you could also let gcc handle it for you:
struct mystruct
{
int num;
char string[0];
};
#define MY_MACRO(_num, _string)\
{ static struct mystruct entry __attribute__ ((section (".my_section"))) = { _num, _string }; }

Resources