libc.s 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. strlen_diy:
  2. mv a5,a0
  3. .L2:
  4. lbu a4,0(a5)
  5. addi a5,a5,1
  6. bne a4,zero,.L2
  7. sub a0,a5,a0
  8. addi a0,a0,-1
  9. ret
  10. memchr_diy:
  11. andi a1,a1,0xff
  12. .L5:
  13. beq a2,zero,.L8
  14. lbu a5,0(a0)
  15. bne a5,a1,.L7
  16. ret
  17. .L7:
  18. addi a0,a0,1
  19. addi a2,a2,-1
  20. j .L5
  21. .L8:
  22. li a0,0
  23. ret
  24. strnlen_diy:
  25. addi sp,sp,-32
  26. sd s0,16(sp)
  27. mv a2,a1
  28. mv s0,a1
  29. li a1,0
  30. sd s1,8(sp)
  31. sd ra,24(sp)
  32. mv s1,a0
  33. call memchr_diy
  34. beq a0,zero,.L10
  35. sub s0,a0,s1
  36. .L10:
  37. ld ra,24(sp)
  38. mv a0,s0
  39. ld s0,16(sp)
  40. ld s1,8(sp)
  41. addi sp,sp,32
  42. jr ra
  43. strcpy_diy:
  44. mv a5,a0
  45. .L16:
  46. lbu a4,0(a1)
  47. addi a1,a1,1
  48. addi a5,a5,1
  49. sb a4,-1(a5)
  50. bne a4,zero,.L16
  51. ret
  52. strcat_diy:
  53. addi sp,sp,-32
  54. sd ra,24(sp)
  55. sd s0,16(sp)
  56. sd a1,8(sp)
  57. mv s0,a0
  58. call strlen_diy
  59. ld a1,8(sp)
  60. add a0,s0,a0
  61. call strcpy_diy
  62. ld ra,24(sp)
  63. mv a0,s0
  64. ld s0,16(sp)
  65. addi sp,sp,32
  66. jr ra
  67. .LC1:
  68. .string "len: %d\n"
  69. .LC2:
  70. .string "Hello C/C++ LIBC:"
  71. .LC3:
  72. .string "-> strcat_diy"
  73. .LC0:
  74. .string "Hello World -> (strlen_diy memchr_diy strcpy_diy strcat_diy)"
  75. .type main, @function
  76. main:
  77. addi sp,sp,-80
  78. sd s0,64(sp)
  79. mv s0,sp
  80. li a2,61
  81. lla a1,.LC0
  82. mv a0,s0
  83. sd ra,72(sp)
  84. call memcpy@plt
  85. mv a0,s0
  86. call strlen_diy
  87. mv a2,a0
  88. li a1,40
  89. mv a0,s0
  90. call memchr_diy
  91. call puts@plt
  92. mv a0,s0
  93. call strlen_diy
  94. sext.w a1,a0
  95. lla a0,.LC1
  96. call printf@plt
  97. li a1,100
  98. mv a0,s0
  99. call strnlen_diy
  100. sext.w a1,a0
  101. lla a0,.LC1
  102. call printf@plt
  103. lla a1,.LC2
  104. mv a0,s0
  105. call strcpy_diy
  106. call puts@plt
  107. lla a1,.LC3
  108. mv a0,s0
  109. call strcat_diy
  110. call puts@plt
  111. ld ra,72(sp)
  112. ld s0,64(sp)
  113. li a0,0
  114. addi sp,sp,80
  115. jr ra