2 ; Ullrich von Bassewitz, 2005-04-21
4 ; int putenv (char* s);
6 ; Note: The function will place s into the environment, *not* a copy!
10 .import _malloc, _free
11 .import searchenv, copyenvptr
12 .import __environ, __envcount, __envsize
14 .import ptr1:zp, ptr2:zp, ptr3:zp, tmp1:zp
20 ;----------------------------------------------------------------------------
27 stx ptr1+1 ; Save name
30 ; Loop over the name to find the '='. If there is no '=', set errno to EINVAL
31 ; and return an error.
38 jmp error ; End of string without '=' found
42 ; Remember the offset of the equal sign and replace it by a zero.
48 ; Search for the string in the environment. searchenv will set the N flag if
49 ; the string is not found, otherwise X contains the index of the entry, ptr2
50 ; contains the entry and Y the offset of the '=' in the string. ptr3 will
51 ; point to the environment.
55 ; Before doing anything else, restore the old environment string.
61 ; Check the result of searchenv
63 txa ; Did we find the entry?
64 bpl addentry ; Jump if yes
66 ; We didn't find the entry, so we have to add a new one. Before doing so, we
67 ; must check if the size of the _environ array must be increased.
68 ; Note: There must be one additional slot for the final NULL entry.
73 bcc addnewentry ; Jump if space enough
75 ; We need to increase the size of the environ array. Calculate the new size.
76 ; We will not support a size larger than 64 entries, double the size with
77 ; each overflow, and the starting size is 8 entries.
81 lda #4 ; Start with 4*2 entries
82 @L2: asl a ; Double current size
83 bmi nomem ; Bail out if > 64
84 sta newsize ; Remember the new size
86 ; Call malloc() and store the result in ptr2
94 ; Check the result of malloc
99 ; Copy the old environment pointer to ptr3, and the new one to __environ.
114 ; Copy the old environment data into the new space.
125 ; Free the old environment space
131 ; Since free() has destroyed ptr2, we need another copy ...
133 jsr copyenvptr ; Copy __environ to ptr2
135 ; Bump the environment count and remember it in X. Add the final NULL entry.
148 ; The index of the new entry is the old environment count.
153 ; Add the new entry to the slot with index in X. The pointer to the environment
154 ; is already in ptr2, either by a call to searchenv, or by above code.
172 error: jsr __seterrno
180 ;----------------------------------------------------------------------------
185 name: .addr 0 ; Pointer to name
186 newsize: .byte 0 ; New environment size