copyProtocolList.m 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // TEST_CONFIG
  2. #include "test.h"
  3. #include <string.h>
  4. #include <malloc/malloc.h>
  5. #include <objc/objc-runtime.h>
  6. @protocol Proto1
  7. +(id)proto1ClassMethod;
  8. -(id)proto1InstanceMethod;
  9. @end
  10. void noNullEntries(Protocol * _Nonnull __unsafe_unretained * _Nullable protolist,
  11. unsigned int count)
  12. {
  13. for (unsigned int i = 0; i != count; ++i) {
  14. testassert(protolist[i]);
  15. testassert(protocol_getName(protolist[i]));
  16. testprintf("Protocol[%d/%d]: %p %s\n", i, count, protolist[i], protocol_getName(protolist[i]));
  17. }
  18. }
  19. Protocol* getProtocol(Protocol * _Nonnull __unsafe_unretained * _Nullable protolist,
  20. unsigned int count, const char* name) {
  21. for (unsigned int i = 0; i != count; ++i) {
  22. if (!strcmp(protocol_getName(protolist[i]), name))
  23. return protolist[i];
  24. }
  25. return nil;
  26. }
  27. int main()
  28. {
  29. Protocol * _Nonnull __unsafe_unretained * _Nullable protolist;
  30. unsigned int count;
  31. count = 100;
  32. protolist = objc_copyProtocolList(&count);
  33. testassert(protolist);
  34. testassert(count != 0);
  35. testassert(malloc_size(protolist) >= (count * sizeof(Protocol*)));
  36. noNullEntries(protolist, count);
  37. testassert(protolist[count] == nil);
  38. // Check for a shared cache protocol, ie, the one we know comes from libobjc
  39. testassert(getProtocol(protolist, count, "NSObject"));
  40. // Test for a protocol we know isn't in the cache
  41. testassert(getProtocol(protolist, count, "Proto1") == @protocol(Proto1));
  42. // Test for a protocol we know isn't there
  43. testassert(!getProtocol(protolist, count, "Proto2"));
  44. free(protolist);
  45. // Now add it
  46. Protocol* newproto = objc_allocateProtocol("Proto2");
  47. objc_registerProtocol(newproto);
  48. Protocol * _Nonnull __unsafe_unretained * _Nullable newProtolist;
  49. unsigned int newCount;
  50. newCount = 100;
  51. newProtolist = objc_copyProtocolList(&newCount);
  52. testassert(newProtolist);
  53. testassert(newCount == (count + 1));
  54. testassert(getProtocol(newProtolist, newCount, "Proto2"));
  55. free(newProtolist);
  56. succeed(__FILE__);
  57. return 0;
  58. }