vlm / asn1c

The ASN.1 Compiler
http://lionet.info/asn1c/
BSD 2-Clause "Simplified" License
1.04k stars 556 forks source link

asn_encode_to_buffer() successfully returning the no of of bytes writtern , but actually not writing to the buffer #460

Open samrajput1143 opened 2 years ago

samrajput1143 commented 2 years ago

asn_encode_to_buffer() is returning the no of bytes written (in my case 67) to char buffer , but when printing the length of that char buffer it comes out to be zero.

same case is happening with asn_encode_to_new_buffer() it is returning a structure whose data member buffer (pointer to void ) , which is not null. And still the length of this buffer is zero

samrajput1143 commented 2 years ago

I'm trying with ATS_ALIGNED_BASIC_PER and ATS_ALIGNED_CANONICAL_PER as the encoding rule.

Also printed the constructed object as XER encoded (XML) xer_fprint(), and it is printing perfectly fine.

Berendej commented 1 year ago

The root of a problem lays in overrun_encoder_cb() which returns 0 even if the buffer is overrun. On the first sight it seems OK for overrun_encoder_cb() . According to comments, it is intended for:

_Encoder which doesn't stop counting bytes even if it reaches the end of the buffer._

BUT overrun_encoder_cb() used by asn_encode_to_buffer() ! There is a dirty solution :

overrun_encoder_cb(const void *data, size_t size, void *keyp) {....
    if(key->computed_size + size > key->buffer_size) {
        key->buffer_size = 0;
        return -1;   <<<<<<<<<<<<<- add this

In this case return of the asn_encode_to_buffer() is much more relevant to what happened. It contains encoded == -1 and failed type description. Still it would be better if encoded would contained the number of bytes which was actually copied to buffer, not -1. If it returns 0 then returned result of a asn_encode_to_buffer() is the same in case when buffer is sufficient and when buffer is not big enough.

If we make it return -1 then overrun_encoder_cb() won't be doing what it was intended to do according to comments. On the other side it's not used elsewhere but in asn_encode_to_buffer() so it's safe.

IMHO if overrun_encoder_cb() is intended to be used only inside of asn_encode_to_buffer() , then 1 ) it must return -1 when the length of a buffer is not sufficient 2) the name and comments to this function should be changed to something like check_and_copy_if_ok()