]> git.sur5r.net Git - cc65/blob - libsrc/common/strdup.s
Merge pull request #310 from groessler/atari-exec-devel
[cc65] / libsrc / common / strdup.s
1 ;
2 ; Ullrich von Bassewitz, 18.07.2000
3 ;
4 ; char* __fastcall__ strdup (const char* S);
5 ;
6 ; Note: The code knowns which zero page locations are used by malloc.
7 ;
8
9         .importzp       sp, tmp1, ptr4
10         .import         pushax, decsp4, incsp4
11         .import         _strlen, _malloc, _memcpy
12         .export         _strdup
13
14         .macpack        cpu
15         .macpack        generic
16
17 _strdup:
18
19 ; Since we need some place to store the intermediate results, allocate a
20 ; stack frame. To make this somewhat more efficient, create the stackframe
21 ; as needed for the final call to the memcpy function.
22
23         pha                     ; decsp will destroy A (but not X)
24         jsr     decsp4          ; Target/source
25
26 ; Store the pointer into the source slot
27
28         ldy     #1
29         txa
30         sta     (sp),y
31         pla
32 .if (.cpu .bitand CPU_ISET_65SC02)
33         sta     (sp)
34 .else
35         dey
36         sta     (sp),y
37 .endif
38
39 ; Get length of S (which is still in a/x)
40
41         jsr     _strlen
42
43 ; Calculate strlen(S)+1 (the space needed)
44
45         add     #1
46         bcc     @L1
47         inx
48
49 ; Save the space we're about to allocate in ptr4
50
51 @L1:    sta     ptr4
52         stx     ptr4+1
53
54 ; Allocate memory. _malloc will not use ptr4
55
56         jsr     _malloc
57
58 ; Store the result into the target stack slot
59
60         ldy     #2
61         sta     (sp),y          ; Store low byte
62         sta     tmp1
63         txa                     ; Get high byte
64         iny
65         sta     (sp),y          ; Store high byte
66
67 ; Check for a NULL pointer
68
69         ora     tmp1
70         beq     OutOfMemory
71
72 ; Copy the string. memcpy will return the target string which is exactly
73 ; what we need here. It will also drop the allocated stack frame.
74
75         lda     ptr4
76         ldx     ptr4+1          ; Load size
77         jmp     _memcpy         ; Copy string, drop stackframe
78
79 ; Out of memory, return NULL (A = 0)
80
81 OutOfMemory:
82         tax
83         jmp     incsp4          ; Drop stack frame
84
85